NNext.js 中文网 GitHub

Next.js 编译器

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

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

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

为什么选择 SWC?#

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

SWC 可用于编译、压缩、打包等,并且在设计上支持扩展。你可以调用它来执行代码转换(无论是内置的还是自定义的)。这些转换通常通过更高层的工具(如 Next.js)来运行。

我们选择基于 SWC 构建,有几个原因:

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

支持的功能#

Styled Components#

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

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

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

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

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

next.config.js
module.exports = {
  compiler: {
    // 有关这些选项的更多信息,请参见 https://styled-components.com/docs/tooling#babel-plugin。
    styledComponents: {
      // 在开发环境中默认启用,在生产环境中禁用以减小文件体积,
      // 设置此选项会覆盖所有环境的默认行为。
      displayName?: boolean,
      // 默认启用。
      ssr?: boolean,
      // 默认启用。
      fileName?: boolean,
      // 默认为空。
      topLevelImportPaths?: string[],
      // 默认为 ["index"]。
      meaninglessFileNames?: string[],
      // 默认启用。
      minify?: boolean,
      // 默认启用。
      transpileTemplateLiterals?: boolean,
      // 默认为空。
      namespace?: string,
      // 默认禁用。
      pure?: boolean,
      // 默认启用。
      cssProp?: boolean,
    },
  },
}

Jest#

Next.js Compiler 会转换你的测试,并简化 Jest 与 Next.js 的联合配置,包括:

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

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

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

// 提供 Next.js 应用的路径,以便加载 next.config.js 和 .env 文件
const createJestConfig = nextJest({ dir: './' })

// 你想传递给 Jest 的任何自定义配置
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}

// 以这种方式导出 createJestConfig,是为了确保 next/jest 能够加载异步的 Next.js 配置
module.exports = createJestConfig(customJestConfig)

Relay#

要启用 Relay 支持:

next.config.js
module.exports = {
  compiler: {
    relay: {
      // 此路径应与 relay.config.js 中的配置一致
      src: './',
      artifactDirectory: './__generated__',
      language: 'typescript',
      eagerEsModules: false,
    },
  },
}

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

移除 React 属性#

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

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

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

要移除自定义属性:

next.config.js
module.exports = {
  compiler: {
    // 此处定义的正则表达式由 Rust 处理,因此语法与 JavaScript 的 `RegExp` 不同。
    // 请参见 https://docs.rs/regex。
    reactRemoveProperties: { properties: ['^data-custom$'] },
  },
}

移除 Console#

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

移除所有 console.* 调用:

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

移除除 console.error 之外的所有 console.* 输出:

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

旧版装饰器#

Next.js 会自动检测 jsconfig.json 或 tsconfig.json 中的 experimentalDecorators。旧版装饰器通常与 mobx 等较旧版本的库一起使用。

此标志仅为兼容现有应用而支持。我们不建议在新应用中使用旧版装饰器。

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

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

importSource#

Next.js 会自动检测 jsconfig.json 或 tsconfig.json 中的 jsxImportSource 并加以应用。这通常用于 Theme UI 等库。

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

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

Emotion#

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

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

next.config.js

module.exports = {
  compiler: {
    emotion: boolean | {
      // 默认为 true。当构建类型为 production 时会被禁用。
      sourceMap?: boolean,
      // 默认为 'dev-only'。
      autoLabel?: 'never' | 'dev-only' | 'always',
      // 默认为 '[local]'。
      // 允许的值:[local]、[filename] 和 [dirname]
      // 此选项仅在 autoLabel 设置为 'dev-only' 或 'always' 时生效。
      // 它允许你定义最终标签的格式。
      // 格式通过字符串定义,其中变量部分用方括号 [] 括起来。
      // 例如 labelFormat: "my-classname--[local]",其中 [local] 会被替换为结果所赋值给的变量名。
      labelFormat?: string,
      // 默认值为 undefined。
      // 此选项用于告诉编译器应关注哪些导入,
      // 以确定需要转换的内容,因此即使你重新导出了 Emotion 的导出项,
      // 仍然可以使用转换。
      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.js
module.exports = {
  transpilePackages: ['@acme/ui', 'lodash-es'],
}

导入模块化#

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

Define(在构建时替换变量)#

define 选项允许你在构建时静态替换代码中的变量。 该选项接受一个对象作为键值对,其中键是需要被对应值替换的变量。

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

next.config.js
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 Compiler 支持生命周期钩子,允许你在构建过程中的特定节点运行自定义代码。目前支持以下钩子:

runAfterProductionCompile#

该钩子函数在生产构建编译完成后、运行类型检查和静态页面生成等编译后任务之前执行。它提供对项目元数据的访问,包括项目目录和构建输出目录,因此第三方工具可以收集 sourcemap 等构建产物。

next.config.js
module.exports = {
  compiler: {
    runAfterProductionCompile: async ({ distDir, projectDir }) => {
      // 在此处添加你的自定义代码
    },
  },
}

该钩子接收一个具有以下属性的对象:

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

实验性功能#

SWC Trace 性能分析#

你可以生成 SWC 内部的转换跟踪信息,格式为 Chromium 的跟踪事件格式。

next.config.js
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 的转换,以使用 SWC 用 wasm 编写实验性插件支持,从而自定义转换行为。

next.config.js
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.0SWC Minifier 稳定版。
v12.2.0增加SWC 插件实验性支持。
v12.1.0增加对 Styled Components、Jest、Relay、移除 React 属性、旧版装饰器、移除 Console 和 jsxImportSource 的支持。
v12.0.0Next.js Compiler 引入。
Next.js 中文网