Next.js 可以通过项目根目录下的 next.config.js 文件(例如,与 package.json 同级)进行配置,该文件需导出一个默认配置对象。
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
}
module.exports = nextConfignext.config.js 是一个常规的 Node.js 模块,而非 JSON 文件。它被 Next.js 服务器和构建阶段使用,但不会包含在浏览器构建中。
如果你需要 ECMAScript 模块,可以使用 next.config.mjs:
// @ts-check
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
export default nextConfig值得注意的是:目前不支持使用
.cjs或.cts扩展名的next.config文件。
你也可以使用一个函数:
// @ts-check
export default (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}从 Next.js 12.1.0 开始,你可以使用异步函数:
// @ts-check
module.exports = async (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}phase 是加载配置的当前上下文。你可以查看 可用阶段。阶段可以从 next/constants 导入:
// @ts-check
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
module.exports = (phase, { defaultConfig }) => {
if (phase === PHASE_DEVELOPMENT_SERVER) {
return {
/* development only config options here */
}
}
return {
/* config options for all phases except development here */
}
}如果在项目中使用 TypeScript,可以使用 next.config.ts 在配置中使用 TypeScript:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
/* config options here */
}
export default nextConfig注释掉的行是你可以放置 next.config.js 允许的配置选项的地方,这些选项 在此文件中定义。
然而,所有这些配置都不是必需的,也没有必要理解每个配置的作用。相反,请在此部分中搜索你需要启用或修改的功能,它们会告诉你具体该怎么做。
避免使用在你的目标 Node.js 版本中不可用的新 JavaScript 特性。
next.config.js不会被 Webpack 或 Babel 解析。
此页面记录了所有可用的配置选项:
从 Next.js 15.1 开始,next/experimental/testing/server 包包含有助于单元测试 next.config.js 文件的实用工具。
函数 unstable_getResponseFromNextConfig 会使用提供的请求信息运行 next.config.js 中的 headers、redirects 和 rewrites 函数,并返回带有路由结果的 NextResponse。
unstable_getResponseFromNextConfig的响应只考虑next.config.js字段,不考虑代理或文件系统路由,因此生产环境中的结果可能与单元测试不同。
import {
getRedirectUrl,
unstable_getResponseFromNextConfig,
} from 'next/experimental/testing/server'
const response = await unstable_getResponseFromNextConfig({
url: 'https://nextjs.org/test',
nextConfig: {
async redirects() {
return [{ source: '/test', destination: '/test2', permanent: false }]
},
},
})
expect(response.status).toEqual(307)
expect(getRedirectUrl(response)).toEqual('https://nextjs.org/test2')