NextJs使用build命令时最终的界面的js文件和css文件全部404的解决

作者:Administrator 发布时间: 2024-07-10 阅读量:2

问题描述

next.config.json

/** @type {import('next').NextConfig} */
const nextConfig = {
    output: 'standalone',
};

export default nextConfig;

在执行 npm run build 时发现实际的页面只有文字,样式和逻辑全部丢失

image-20240710210533286

打开开发者工具发现外部文件全部报404

image-20240710210635458

问题解析

根据官方文档1

Additionally, a minimal server.js file is also output which can be used instead of next start. This minimal server does not copy the public or .next/static folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the standalone/public and standalone/.next/static folders manually, after which server.js file will serve these automatically.

在使用“standalone”作为选项时,next会将css、js等文件排除在外,官方建议将这些静态资源通过CDN来引入

问题解决2

方法一

手动将.next/static文件夹的文件复制到.next/standalone/.next/static

方法二

修改package.json中的build命令,变为

"build": "next build && cp -r .next/static .next/standalone/.next/ && cp -r public .next/standalone/"

问题即可解决

image-20240710212944451

注意

在Powershell和cmd中都没有cp命令,这是需要用 git bash解决

参考资料