跳至内容
App 路由API 参考next.config.js 选项

next.config.js 选项

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

next.config.js
// @ts-check
 
/** @type {import('next').NextConfig} */
const nextConfig = {
  /* config options here */
}
 
module.exports = nextConfig

ECMAScript 模块

next.config.js 是一个普通的 Node.js 模块,而不是 JSON 文件。它被 Next.js 服务器和构建阶段使用,并且不包含在浏览器构建中。

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

next.config.mjs
// @ts-check
 
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  /* config options here */
}
 
export default nextConfig

注意:目前**不支持**使用 .cjs.cts.mts 扩展名的 next.config

配置作为函数

你也可以使用函数

next.config.mjs
// @ts-check
 
export default (phase, { defaultConfig }) => {
  /**
   * @type {import('next').NextConfig}
   */
  const nextConfig = {
    /* config options here */
  }
  return nextConfig
}

异步配置

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

next.config.js
// @ts-check
 
module.exports = async (phase, { defaultConfig }) => {
  /**
   * @type {import('next').NextConfig}
   */
  const nextConfig = {
    /* config options here */
  }
  return nextConfig
}

阶段

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

next.config.js
// @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.js 预览版中可用。

如果你在项目中使用 TypeScript,则可以使用next.config.ts在配置中使用 TypeScript

next.config.ts
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 解析。

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

appDir

Enable the App Router to use layouts, streaming, and more.

assetPrefix

Learn how to use the assetPrefix config option to configure your CDN.

basePath

Use `basePath` to deploy a Next.js application under a sub-path of a domain.

compress

Next.js provides gzip compression to compress rendered content and static files, it only works with the server target. Learn more about it here.

crossOrigin

Use the `crossOrigin` option to add a crossOrigin tag on the `script` tags generated by `next/script`.

cssChunking

Use the `cssChunking` option to control how CSS files are chunked in your Next.js application.

devIndicators

Optimized pages include an indicator to let you know if it's being statically optimized. You can opt-out of it here.

distDir

Set a custom build directory to use instead of the default .next directory.

env

Learn to add and access environment variables in your Next.js application at build time.

eslint

Next.js reports ESLint errors and warnings during builds by default. Learn how to opt-out of this behavior here.

expireTime

Customize stale-while-revalidate expire time for ISR enabled pages.

exportPathMap

Customize the pages that will be exported as HTML files when using `next export`.

generateBuildId

Configure the build id, which is used to identify the current build in which your application is being served.

generateEtags

Next.js will generate etags for every page by default. Learn more about how to disable etag generation here.

headers

Add custom HTTP headers to your Next.js app.

httpAgentOptions

Next.js will automatically use HTTP Keep-Alive by default. Learn more about how to disable HTTP Keep-Alive here.

images

Custom configuration for the next/image loader

cacheHandler

Configure the Next.js cache used for storing and revalidating data to use any external service like Redis, Memcached, or others.

logging

Configure how data fetches are logged to the console when running Next.js in development mode.

mdxRs

Use the new Rust compiler to compile MDX files in the App Router.

onDemandEntries

Configure how Next.js will dispose and keep in memory pages created in development.

optimizePackageImports

API Reference for optimizePackageImports Next.js Config Option

output

Next.js automatically traces which files are needed by each page to allow for easy deployment of your application. Learn how it works here.

pageExtensions

Extend the default page extensions used by Next.js when resolving pages in the Pages Router.

poweredByHeader

Next.js will add the `x-powered-by` header by default. Learn to opt-out of it here.

ppr

Learn how to enable Partial Prerendering in Next.js.

productionBrowserSourceMaps

Enables browser source map generation during the production build.

reactCompiler

Enable the React Compiler to automatically optimize component rendering.

reactMaxHeadersLength

The maximum length of the headers that are emitted by React and added to the response.

reactStrictMode

The complete Next.js runtime is now Strict Mode-compliant, learn how to opt-in

redirects

Add redirects to your Next.js app.

rewrites

Add rewrites to your Next.js app.

sassOptions

Configure Sass options.

serverActions

Configure Server Actions behavior in your Next.js application.

serverComponentsHmrCache

Configure whether fetch responses in Server Components are cached across HMR refresh requests.

serverExternalPackages

Opt-out specific dependencies from the Server Components bundling and use native Node.js `require`.

staleTimes

Learn how to override the invalidation time of the Client Router Cache.

staticGeneration*

Learn how to configure static generation in your Next.js application.

trailingSlash

Configure Next.js pages to resolve with or without a trailing slash.

transpilePackages

Automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (`node_modules`).

turbo

Configure Next.js with Turbopack-specific options

typedRoutes

Enable experimental support for statically typed links.

typescript

Next.js reports TypeScript errors by default. Learn to opt-out of this behavior here.

urlImports

Configure Next.js to allow importing modules from external URLs.

useLightningcss

Enable experimental support for Lightning CSS.

webpack

Learn how to customize the webpack config used by Next.js

webVitalsAttribution

Learn how to use the webVitalsAttribution option to pinpoint the source of Web Vitals issues.