N Next.js 中文
原文 ↗

Next.js 编译器

Next.js 编译器使用 Rust 编写,用于转换和压缩你的 Next.js 应用。

更新于 2025-05-19Next.js 16.4.6

Next.js 编译器使用 Rust 编写并基于 SWC,使 Next.js 能够为生产环境转换和压缩你的 JavaScript 代码。它取代了针对单个文件的 Babel,以及用于压缩输出包的 Terser。

使用 Next.js 编译器进行编译比 Babel 快 17 倍,并且自 Next.js 12 起默认启用。如果你已有 Babel 配置,或正在使用不受支持的功能,你的应用将退出 Next.js 编译器,继续使用 Babel。

为什么选择 SWC?

SWC 是一个可扩展的、基于 Rust 的平台,面向下一代快速开发者工具。

SWC 可用于编译、压缩、打包等,并且被设计为可扩展的。你可以调用它来执行代码转换(内置或自定义)。这些转换通过像 Next.js 这样的更高层工具来执行。

我们选择基于 SWC 构建,原因有以下几点:

  • 可扩展性: SWC 可以作为 crate 在 Next.js 内部使用,无需 fork 该库或绕过设计限制。
  • 性能: 通过切换到 SWC,我们在 Next.js 中实现了约快 3 倍的 Fast Refresh 和约快 5 倍的构建速度,并且还有更多优化空间仍在推进中。
  • WebAssembly: Rust 对 WASM 的支持对于支持所有可能的平台、让 Next.js 开发无处不在至关重要。
  • 社区: Rust 社区和生态系统非常出色,并且仍在不断成长。

支持的功能

Styled Components

我们正在努力将 babel-plugin-styled-components 移植到 Next.js 编译器。

首先,更新到 Next.js 的最新版本:npm install next@latest。然后,更新你的 next.config.js 文件:

next.config.jsjs
module.exports = {
  compiler: {
    styledComponents: true,
  },
}

对于高级用例,你可以为 styled-components 编译配置各项属性。

注意:ssr 和 displayName 转换是在 Next.js 中使用 styled-components 的主要前提。

next.config.jsjs
module.exports = {
  compiler: {
    // see https://styled-components.com/docs/tooling#babel-plugin for more info on the options.
    styledComponents: {
      // Enabled by default in development, disabled in production to reduce file size,
      // setting this will override the default for all environments.
      displayName?: boolean,
      // Enabled by default.
      ssr?: boolean,
      // Enabled by default.
      fileName?: boolean,
      // Empty by default.
      topLevelImportPaths?: string[],
      // Defaults to ["index"].
      meaninglessFileNames?: string[],
      // Enabled by default.
      minify?: boolean,
      // Enabled by default.
      transpileTemplateLiterals?: boolean,
      // Empty by default.
      namespace?: string,
      // Disabled by default.
      pure?: boolean,
      // Enabled by default.
      cssProp?: boolean,
    },
  },
}

Jest

Next.js 编译器会转译你的测试,并简化将 Jest 与 Next.js 一同配置的过程,包括:

  • 自动模拟 .css、.module.css(及其 .scss 变体)以及图片导入
  • 使用 SWC 自动配置 transform
  • 将 .env(及所有变体)加载到 process.env 中
  • 在测试解析和转换中忽略 node_modules
  • 在测试解析中忽略 .next
  • 为启用实验性 SWC 转换的标志加载 next.config.js

首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新你的 jest.config.js 文件:

jest.config.jsjs
const nextJest = require('next/jest')

// Providing the path to your Next.js app which will enable loading next.config.js and .env files
const createJestConfig = nextJest({ dir: './' })

// Any custom config you want to pass to Jest
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}

// createJestConfig is exported in this way to ensure that next/jest can load the Next.js configuration, which is async
module.exports = createJestConfig(customJestConfig)

Relay

要启用 Relay 支持:

next.config.jsjs
module.exports = {
  compiler: {
    relay: {
      // This should match relay.config.js
      src: './',
      artifactDirectory: './__generated__',
      language: 'typescript',
      eagerEsModules: false,
    },
  },
}

须知:

在 Next.js 中,pages 目录下的所有 JavaScript 文件都被视为路由。因此,对于 relay-compiler,你需要在 pages 之外指定 artifactDirectory 配置设置,否则 relay-compiler 会在 __generated__ 目录中的源文件旁生成文件,而该文件将被视为路由,从而破坏生产构建。

移除 React 属性

允许移除 JSX 属性。这通常用于测试。类似于 babel-plugin-react-remove-properties。

要移除匹配默认正则表达式 ^data-test 的属性:

next.config.jsjs
module.exports = {
  compiler: {
    reactRemoveProperties: true,
  },
}

要移除自定义属性:

next.config.jsjs
module.exports = {
  compiler: {
    // The regexes defined here are processed in Rust so the syntax is different from
    // JavaScript `RegExp`s. See https://docs.rs/regex.
    reactRemoveProperties: { properties: ['^data-custom$'] },
  },
}

移除 Console

该转换允许移除应用代码中的所有 console.* 调用(不包括 node_modules)。类似于 babel-plugin-transform-remove-console。

移除所有 console.* 调用:

next.config.jsjs
module.exports = {
  compiler: {
    removeConsole: true,
  },
}

移除 console.* 输出,但保留 console.error:

next.config.jsjs
module.exports = {
  compiler: {
    removeConsole: {
      exclude: ['error'],
    },
  },
}

旧版装饰器

Next.js 会自动检测 jsconfig.json 或 tsconfig.json 中的 experimentalDecorators。旧版装饰器常用于旧版本的库(如 mobx)。

此标志仅出于与现有应用程序兼容的目的而受支持。我们不建议在新应用程序中使用旧版装饰器。

首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新你的 jsconfig.json 或 tsconfig.json 文件:

{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

importSource

Next.js 会自动检测 jsconfig.json 或 tsconfig.json 中的 jsxImportSource 并应用它。这通常与 Theme UI 等库一起使用。

首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新你的 jsconfig.json 或 tsconfig.json 文件:

{
  "compilerOptions": {
    "jsxImportSource": "theme-ui"
  }
}

Emotion

我们正在努力将 @emotion/babel-plugin 移植到 Next.js 编译器。

首先,更新到 Next.js 的最新版本:npm install next@latest。然后,更新你的 next.config.js 文件:

next.config.jsjs

module.exports = {
  compiler: {
    emotion: boolean | {
      // default is true. It will be disabled when build type is production.
      sourceMap?: boolean,
      // default is 'dev-only'.
      autoLabel?: 'never' | 'dev-only' | 'always',
      // default is '[local]'.
      // Allowed values: `[local]` `[filename]` and `[dirname]`
      // This option only works when autoLabel is set to 'dev-only' or 'always'.
      // It allows you to define the format of the resulting label.
      // The format is defined via string where variable parts are enclosed in square brackets [].
      // For example labelFormat: "my-classname--[local]", where [local] will be replaced with the name of the variable the result is assigned to.
      labelFormat?: string,
      // default is undefined.
      // This option allows you to tell the compiler what imports it should
      // look at to determine what it should transform so if you re-export
      // Emotion's exports, you can still use transforms.
      importMap?: {
        [packageName: string]: {
          [exportName: string]: {
            canonicalImport?: [string, string],
            styledBaseImport?: [string, string],
          }
        }
      },
    },
  },
}

代码压缩

自 v13 起,Next.js 的 swc 编译器默认用于代码压缩。这比 Terser 快 7 倍。

值得了解:

从 v15 开始,无法使用 next.config.js 自定义代码压缩。对 swcMinify 标志的支持已被移除。

模块转译

Next.js 可以自动转译并打包来自本地包(如 monorepo)或外部依赖(node_modules)的依赖项。这取代了 next-transpile-modules 包。

next.config.jsjs
module.exports = {
  transpilePackages: ['@acme/ui', 'lodash-es'],
}

模块化导入

在 Next.js 13.5 中,此选项已被 optimizePackageImports 取代。我们建议升级以使用无需手动配置导入路径的新选项。

Define(在构建期间替换变量)

define 选项允许你在构建时静态替换代码中的变量。 该选项接受一个以键值对形式表示的对象,其中键是要用对应值替换的变量。

使用 next.config.js 中的 compiler.define 字段为所有环境(服务器、边缘和客户端)定义变量。或者,使用 compiler.defineServer 仅为服务器端(服务器和边缘)代码定义变量:

next.config.jsjs
module.exports = {
  compiler: {
    define: {
      MY_VARIABLE: 'my-string',
      'process.env.MY_ENV_VAR': 'my-env-var',
    },
    defineServer: {
      MY_SERVER_VARIABLE: 'my-server-var',
    },
  },
}

构建生命周期钩子

Next.js 编译器支持生命周期钩子,允许你在构建过程中的特定时间点运行自定义代码。目前支持以下钩子:

runAfterProductionCompile

一个钩子函数,在生产构建编译完成后、但在运行类型检查和静态页面生成等编译后任务之前执行。该钩子提供对项目元数据(包括项目目录和构建输出目录)的访问,这对于第三方工具收集 sourcemap 等构建输出很有用。

next.config.jsjs
module.exports = {
  compiler: {
    runAfterProductionCompile: async ({ distDir, projectDir }) => {
      // Your custom code here
    },
  },
}

该钩子接收一个包含以下属性的对象:

  • distDir:构建输出目录(默认为 .next)
  • projectDir:项目的根目录

实验性功能

SWC Trace 性能分析

你可以按照 Chromium 的 跟踪事件格式 生成 SWC 的内部转换跟踪记录。

next.config.jsjs
module.exports = {
  experimental: {
    swcTraceProfiling: true,
  },
}

启用后,swc 将在 .next/ 下生成名为 swc-trace-profile-${timestamp}.json 的跟踪文件。Chromium 的跟踪查看器(chrome://tracing/,https://ui.perfetto.dev/)或兼容的火焰图查看器(https://www.speedscope.app/)可以加载并可视化生成的跟踪记录。

SWC 插件(实验性)

你可以配置 swc 的 transform,借助 SWC 以 wasm 编写的实验性插件支持来自定义转换行为。

next.config.jsjs
module.exports = {
  experimental: {
    swcPlugins: [
      [
        'plugin',
        {
          ...pluginOptions,
        },
      ],
    ],
  },
}

swcPlugins 接受一个由元组组成的数组来配置插件。插件的元组包含插件路径和一个用于插件配置的对象。插件路径可以是 npm 模块包名,也可以是 .wasm 二进制文件本身的绝对路径。

不支持的功能

当你的应用包含 .babelrc 文件时,Next.js 会自动回退到使用 Babel 来转换单个文件。这确保了与利用自定义 Babel 插件的现有应用之间的向后兼容性。

如果你使用的是自定义 Babel 配置,请分享你的配置。我们正在努力移植尽可能多的常用 Babel 转换,并在未来支持插件。

版本历史

版本 变更
v13.1.0 模块转译 和 模块化导入 已稳定。
v13.0.0 默认启用 SWC Minifier。
v12.3.0 SWC Minifier 已稳定。
v12.2.0 新增了对 SWC 插件 的实验性支持。
v12.1.0 新增了对 Styled Components、Jest、Relay、Remove React Properties、Legacy Decorators、Remove Console 和 jsxImportSource 的支持。
v12.0.0 Next.js Compiler 引入。