前言
Next.js 可以通过根目录的next.config.js
进行配置
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
};
module.exports = nextConfig;
正如文件的扩展名是 .js,next.config.js 是一个常规的 Node.js 模块,而不是一个 JSON 文件。它会在 Next.js server 和构建阶段被用到,并且不包含在浏览器构建中(代码不会打包到客户端)。
如果你需要 ECMAScript 模块,你可以使用 next.config.mjs
:
参数
assetPrefix
assetPrefix 用于设置资源前缀,举个例子:
// next.config.js
const isProd = process.env.NODE_ENV === "production";
module.exports = {
// Use the CDN in production and localhost for development.
assetPrefix: isProd ? "https://cdn.mydomain.com" : undefined,
};
Next.js 会自动为从 /\_next
路径(.next/static/文件夹
)加载的 JavaScript
和 CSS
文件添加资源前缀。
以这个例子为例,当请求 JS 代码片段的时候,原本地址是:
/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
现在变成了:
https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
basePath
basePath
用于打包后不是根目录.用于二级目录部署
- 代码
const nextConfig = {
basePath: "/docs",
};
export default nextConfig;
- 访问
https://yourdomain.com/docs/
compress
Next.js 提供 gzip 压缩来压缩渲染的内容和静态文件。如果你想禁用压缩功能:
// next.config.js
const nextConfig = {
compress: false,
};
export default nextConfig;
devIndicators
当你编辑代码,Next.js 正在编译应用的时候,页面右下角会有一个编译指示器。
这个指示器只会在开发模式下展示,生产环境中不会展示。如果你想更改它的位置,就比如它跟页面的其他元素位置发生冲突了:
const nextConfig = {
devIndicators: {
buildActivityPosition: "bottom-right",
},
};
export default nextConfig;
默认值是 bottom-right
,其他值还有 bottom-left
、top-right
、top-left
。
如果你想禁用:
const nextConfig = {
devIndicators: {
buildActivity: false,
},
};
export default nextConfig;
distDir
distDir 用于自定义构建目录,默认是 .next
:
举个例子:
const nextConfig = {
distDir: "build",
};
export default nextConfig;
现在如果你运行 next build
,Next.js
会使用 build
文件夹而不是 .next
文件夹。注意:distDir
不能离开你的项目目录,举个例子,../build
就是一个无效目录。
eslint
如果项目中检测到 ESLint,Next.js 会在出现错误的时候,让生产构建(next build)失败。
如果你希望即使有错误,也要构建生产代码,可以禁止内置的 ESLint:
const nextConfig = {
eslint: {
ignoreDuringBuilds: true,
},
};
export default nextConfig;