Skip to main content

next.config.js 选项

Next.js 可以通过项目根目录中的 next.config.js 文件(例如,通过 package.json)使用默认导出进行配置。

¥Next.js can be configured through a next.config.js file in the root of your project directory (for example, by package.json) with a default export.

// @ts-check

/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
}

module.exports = nextConfig

next.config.js 是常规 Node.js 模块,而不是 JSON 文件。它由 Next.js 服务器和构建阶段使用,并且不包含在浏览器构建中。

¥next.config.js is a regular Node.js module, not a JSON file. It gets used by the Next.js server and build phases, and it's not included in the browser build.

如果需要 ECMAScript 模块,可以使用 next.config.mjs

¥If you need ECMAScript modules, you can use next.config.mjs:

// @ts-check

/**

* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}

export default nextConfig

你还可以使用一个函数:

¥You can also use a function:

// @ts-check

export default (phase, { defaultConfig }) => {
/**

* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}

从 Next.js 12.1.0 开始,你可以使用异步函数:

¥Since Next.js 12.1.0, you can use an async function:

// @ts-check

module.exports = async (phase, { defaultConfig }) => {
/**

* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}

phase 是加载配置的当前上下文。你可以看到 可用阶段。可以从 next/constants 导入相:

¥phase is the current context in which the configuration is loaded. You can see the available phases. Phases can be imported from 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 */
}
}

注释行是可以放置 next.config.js 允许的配置的地方,即 该文件中定义的

¥The commented lines are the place where you can put the configs allowed by next.config.js, which are defined in this file.

然而,这些配置都不是必需的,也没有必要了解每个配置的作用。相反,在本部分中搜索你需要启用或修改的功能,它们会告诉你该怎么做。

¥However, none of the configs are required, and it's not necessary to understand what each config does. Instead, search for the features you need to enable or modify in this section and they will show you what to do.

避免使用目标 Node.js 版本中不可用的新 JavaScript 功能。next.config.js 不会被 Webpack、Babel 或 TypeScript 解析。

¥Avoid using new JavaScript features not available in your target Node.js version. next.config.js will not be parsed by Webpack, Babel or TypeScript.

此页面记录了所有可用的配置选项:

¥This page documents all the available configuration options: