Skip to main content

Next.js 编译器

Next.js 编译器使用 SWC 用 Rust 编写,允许 Next.js 转换和缩小你的 JavaScript 代码以用于生产。这取代了用于单个文件的 Babel 和用于缩小输出包的 Terser。

¥The Next.js Compiler, written in Rust using SWC, allows Next.js to transform and minify your JavaScript code for production. This replaces Babel for individual files and Terser for minifying output bundles.

使用 Next.js 编译器进行编译的速度比 Babel 快 17 倍,并且从 Next.js 版本 12 开始默认启用。如果你有现有的 Babel 配置或正在使用 不支持的功能,你的应用将选择退出 Next.js 编译器并继续使用 Babel。

¥Compilation using the Next.js Compiler is 17x faster than Babel and enabled by default since Next.js version 12. If you have an existing Babel configuration or are using unsupported features, your application will opt-out of the Next.js Compiler and continue using Babel.

为什么选择 SWC?

¥Why SWC?

SWC 是一个基于 Rust 的可扩展平台,适用于下一代快速开发工具。

¥SWC is an extensible Rust-based platform for the next generation of fast developer tools.

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

¥SWC can be used for compilation, minification, bundling, and more – and is designed to be extended. It's something you can call to perform code transformations (either built-in or custom). Running those transformations happens through higher-level tools like Next.js.

我们选择基于 SWC 进行构建有以下几个原因:

¥We chose to build on SWC for a few reasons:

  • 可扩展性:SWC 可以用作 Next.js 中的 Crate,而无需复刻库或解决设计约束。

    ¥Extensibility: SWC can be used as a Crate inside Next.js, without having to fork the library or workaround design constraints.

  • 表现:通过切换到 SWC,我们能够将 Next.js 中的快速刷新速度提高约 3 倍,并将构建速度提高约 5 倍,并且仍有更多优化空间。

    ¥Performance: We were able to achieve ~3x faster Fast Refresh and ~5x faster builds in Next.js by switching to SWC, with more room for optimization still in progress.

  • WebAssembly:Rust 对 WASM 的支持对于支持所有可能的平台并使 Next.js 开发无处不在至关重要。

    ¥WebAssembly: Rust's support for WASM is essential for supporting all possible platforms and taking Next.js development everywhere.

  • 社区:Rust 社区和生态系统令人惊叹,并且仍在不断发展。

    ¥Community: The Rust community and ecosystem are amazing and still growing.

支持的功能

¥Supported Features

样式组件

¥Styled Components

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

¥We're working to port babel-plugin-styled-components to the Next.js Compiler.

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

¥First, update to the latest version of Next.js: npm install next@latest. Then, update your next.config.js file:

module.exports = {
compiler: {
styledComponents: true,
},
}

对于高级用例,你可以为样式组件编译配置单独的属性。

¥For advanced use cases, you can configure individual properties for styled-components compilation.

注意:minifytranspileTemplateLiteralspure 尚未实现。你可以跟踪进度 此处ssrdisplayName 转换是在 Next.js 中使用 styled-components 的主要要求。

¥Note: minify, transpileTemplateLiterals and pure are not yet implemented. You can follow the progress here. ssr and displayName transforms are the main requirement for using styled-components in Next.js.

module.exports = {
compiler: {
// see https://styled-components.nodejs.cn/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.
cssProp?: boolean,
// Empty by default.
namespace?: string,
// Not supported yet.
minify?: boolean,
// Not supported yet.
transpileTemplateLiterals?: boolean,
// Not supported yet.
pure?: boolean,
},
},
}

Jest

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

¥The Next.js Compiler transpiles your tests and simplifies configuring Jest together with Next.js including:

  • 自动模拟 .css.module.css(及其 .scss 变体)和图片导入

    ¥Auto mocking of .css, .module.css (and their .scss variants), and image imports

  • 使用 SWC 自动设置 transform

    ¥Automatically sets up transform using SWC

  • .env(和所有变体)加载到 process.env

    ¥Loading .env (and all variants) into process.env

  • 从测试解析和转换中忽略 node_modules

    ¥Ignores node_modules from test resolving and transforms

  • 从测试解析中忽略 .next

    ¥Ignoring .next from test resolving

  • 加载 next.config.js 以获取启用实验性 SWC 转换的标志

    ¥Loads next.config.js for flags that enable experimental SWC transforms

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

¥First, update to the latest version of Next.js: npm install next@latest. Then, update your jest.config.js file:

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 支持:

¥To enable Relay support:

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__ 目录中的源文件旁边生成文件,并且该文件将被视为路由,这将破坏生产构建。

¥Good to know: In Next.js, all JavaScript files in pages directory are considered routes. So, for relay-compiler you'll need to specify artifactDirectory configuration settings outside of the pages, otherwise relay-compiler will generate files next to the source file in the __generated__ directory, and this file will be considered a route, which will break production builds.

删除反应属性

¥Remove React Properties

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

¥Allows to remove JSX properties. This is often used for testing. Similar to babel-plugin-react-remove-properties.

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

¥To remove properties matching the default regex ^data-test:

module.exports = {
compiler: {
reactRemoveProperties: true,
},
}

要删除自定义属性:

¥To remove custom properties:

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$'] },
},
}

删除控制台

¥Remove Console

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

¥This transform allows for removing all console.* calls in application code (not node_modules). Similar to babel-plugin-transform-remove-console.

删除所有 console.* 调用:

¥Remove all console.* calls:

module.exports = {
compiler: {
removeConsole: true,
},
}

删除 console.* 输出(console.error 除外):

¥Remove console.* output except console.error:

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

旧版装饰器

¥Legacy Decorators

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

¥Next.js will automatically detect experimentalDecorators in jsconfig.json or tsconfig.json. Legacy decorators are commonly used with older versions of libraries like mobx.

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

¥This flag is only supported for compatibility with existing applications. We do not recommend using legacy decorators in new applications.

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

¥First, update to the latest version of Next.js: npm install next@latest. Then, update your jsconfig.json or tsconfig.json file:

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

importSource

Next.js 将自动检测 jsconfig.jsontsconfig.json 中的 jsxImportSource 并应用它。这通常与 主题界面 这样的库一起使用。

¥Next.js will automatically detect jsxImportSource in jsconfig.json or tsconfig.json and apply that. This is commonly used with libraries like Theme UI.

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

¥First, update to the latest version of Next.js: npm install next@latest. Then, update your jsconfig.json or tsconfig.json file:

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

Emotion

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

¥We're working to port @emotion/babel-plugin to the Next.js Compiler.

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

¥First, update to the latest version of Next.js: npm install next@latest. Then, update your next.config.js file:


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],
}
}
},
},
},
}

缩小化

¥Minification

从 v13 开始,Next.js 的 swc 编译器默认用于缩小。这比 Terser 快 7 倍。

¥Next.js' swc compiler is used for minification by default since v13. This is 7x faster than Terser.

如果出于任何原因仍然需要 Terser,则可以对其进行配置。

¥If Terser is still needed for any reason this can be configured.

module.exports = {
swcMinify: false,
}

模块转译

¥Module Transpilation

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

¥Next.js can automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (node_modules). This replaces the next-transpile-modules package.

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

模块化导入

¥Modularize Imports

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

¥This option has been superseded by optimizePackageImports in Next.js 13.5. We recommend upgrading to use the new option that does not require manual configuration of import paths.

实验特点

¥Experimental Features

SWC 跟踪分析

¥SWC Trace profiling

你可以将 SWC 的内部转换轨迹生成为 chromium 的 跟踪事件格式

¥You can generate SWC's internal transform traces as chromium's trace event format.

module.exports = {
experimental: {
swcTraceProfiling: true,
},
}

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

¥Once enabled, swc will generate trace named as swc-trace-profile-${timestamp}.json under .next/. Chromium's trace viewer (chrome://tracing/, https://ui.perfetto.dev/), or compatible flamegraph viewer (https://www.speedscope.app/) can load & visualize generated traces.

SWC 插件(实验性)

¥SWC Plugins (Experimental)

你可以配置 SWC 的转换以使用以 wasm 编写的 SWC 实验性插件支持来自定义转换行为。

¥You can configure swc's transform to use SWC's experimental plugin support written in wasm to customize transformation behavior.

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

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

¥swcPlugins accepts an array of tuples for configuring plugins. A tuple for the plugin contains the path to the plugin and an object for plugin configuration. The path to the plugin can be an npm module package name or an absolute path to the .wasm binary itself.

不支持的功能

¥Unsupported Features

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

¥When your application has a .babelrc file, Next.js will automatically fall back to using Babel for transforming individual files. This ensures backwards compatibility with existing applications that leverage custom Babel plugins.

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

¥If you're using a custom Babel setup, please share your configuration. We're working to port as many commonly used Babel transformations as possible, as well as supporting plugins in the future.

版本历史

¥Version History

版本变化
v13.1.0模块转译模块化导入 稳定。
v13.0.0SWC Minifier 默认启用。
v12.3.0SWC 缩小器 stable
v12.2.0添加了 SWC 插件 实验支持。
v12.1.0添加了对样式组件、Jest、Relay、Remove React Properties、Legacy Decorators、Remove Console 和 jsxImportSource 的支持。
v12.0.0Next.js 编译器 introduced