Next.js 编译器使用 SWC 用 Rust 编写,允许 Next.js 转换并压缩您的 JavaScript 代码以用于生产环境。这取代了 Babel 处理单个文件以及 Terser 压缩输出包的功能。
使用 Next.js 编译器进行编译比 Babel 快 17 倍,并且自 Next.js 版本 12 起默认启用。如果您有现有的 Babel 配置或正在使用不支持的功能,您的应用程序将选择退出 Next.js 编译器并继续使用 Babel。
SWC 是一个可扩展的基于 Rust 的平台,专为下一代快速开发工具而设计。
SWC 可用于编译、压缩、打包等功能,并且旨在实现可扩展性。您可以调用它来执行代码转换(无论是内置的还是自定义的)。这些转换通过 Next.js 等更高级的工具执行。
我们选择基于 SWC 构建的原因有以下几点:
我们正在努力将 babel-plugin-styled-components 移植到 Next.js 编译器。
首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新您的 next.config.js 文件:
module.exports = {
compiler: {
styledComponents: true,
},
}对于高级用例,您可以为 styled-components 编译配置单个属性。
注意:
ssr和displayName转换是在 Next.js 中使用styled-components的主要要求。
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,
},
},
}Next.js 编译器会转译您的测试,并简化 Jest 与 Next.js 的配置,其中包括:
.css、.module.css(及其 .scss 变体)以及图片导入transform.env(及其所有变体)加载到 process.env 中node_modules.nextnext.config.js 以获取启用实验性 SWC 转换的标志首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新您的 jest.config.js 文件:
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 支持:
module.exports = {
compiler: {
relay: {
// This should match relay.config.js
src: './',
artifactDirectory: './__generated__',
language: 'typescript',
eagerEsModules: false,
},
},
}须知:在 Next.js 中,
pages目录中的所有 JavaScript 文件都被视为路由。因此,对于relay-compiler,您需要将artifactDirectory配置设置指定在pages之外,否则relay-compiler将在__generated__目录中生成与源文件相邻的文件,而该文件将被视为路由,这将导致生产构建失败。
允许移除 JSX 属性。这通常用于测试。类似于 babel-plugin-react-remove-properties。
要移除匹配默认正则表达式 ^data-test 的属性:
module.exports = {
compiler: {
reactRemoveProperties: true,
},
}要移除自定义属性:
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$'] },
},
}此转换允许移除应用程序代码中(而非 node_modules 中)所有的 console.* 调用。类似于 babel-plugin-transform-remove-console。
移除所有 console.* 调用:
module.exports = {
compiler: {
removeConsole: true,
},
}移除 console.* 输出,但保留 console.error:
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
}
}Next.js 将自动检测 jsconfig.json 或 tsconfig.json 中的 jsxImportSource 并应用它。这通常与 Theme UI 等库一起使用。
首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新您的 jsconfig.json 或 tsconfig.json 文件:
{
"compilerOptions": {
"jsxImportSource": "theme-ui"
}
}我们正在努力将 @emotion/babel-plugin 移植到 Next.js 编译器。
首先,更新到最新版本的 Next.js:npm install next@latest。然后,更新您的 next.config.js 文件:
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],
}
}
},
},
},
}Next.js 的 SWC 编译器自 v13 起默认用于压缩。这比 Terser 快 7 倍。
须知: 从 v15 开始,压缩功能不能通过
next.config.js进行自定义。对swcMinify标志的支持已被移除。
Next.js 可以自动转译并打包来自本地包(如单体仓库)或外部依赖项(node_modules)的依赖。这取代了 next-transpile-modules 包。
module.exports = {
transpilePackages: ['@acme/ui', 'lodash-es'],
}此选项已被 Next.js 13.5 中的 optimizePackageImports 取代。我们建议升级以使用无需手动配置导入路径的新选项。
define 选项允许您在构建时静态替换代码中的变量。
该选项接受一个键值对对象,其中键是要替换的变量,值是相应的替换值。
在 next.config.js 中使用 compiler.define 字段为所有环境(服务器、边缘和客户端)定义变量。或者,使用 compiler.defineServer 仅为服务器端(服务器和边缘)代码定义变量:
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 编译器支持生命周期钩子,允许您在构建过程中的特定点运行自定义代码。目前,支持以下钩子:
一个钩子函数,在生产构建编译完成后执行,但在运行类型检查和静态页面生成等编译后任务之前。此钩子提供对项目元数据的访问,包括项目目录和构建输出目录,这使其对于第三方工具收集诸如源映射之类的构建输出非常有用。
module.exports = {
compiler: {
runAfterProductionCompile: async ({ distDir, projectDir }) => {
// Your custom code here
},
},
}该钩子接收一个包含以下属性的对象:
distDir:构建输出目录(默认为 .next)projectDir:项目的根目录您可以将 SWC 的内部转换跟踪生成为 Chromium 的 跟踪事件格式。
module.exports = {
experimental: {
swcTraceProfiling: true,
},
}启用后,SWC 将在 .next/ 下生成名为 swc-trace-profile-${timestamp}.json 的跟踪文件。Chromium 的跟踪查看器 (chrome://tracing/, https://ui.perfetto.dev/) 或兼容的火焰图查看器 (https://www.speedscope.app/) 可以加载并可视化生成的跟踪。
您可以配置 SWC 的转换以使用用 WASM 编写的 SWC 实验性插件支持来定制转换行为。
module.exports = {
experimental: {
swcPlugins: [
[
'plugin',
{
...pluginOptions,
},
],
],
},
}swcPlugins 接受一个用于配置插件的元组数组。插件的元组包含插件的路径和插件配置对象。插件的路径可以是 npm 模块包名,也可以是 .wasm 二进制文件本身的绝对路径。
当您的应用程序具有 .babelrc 文件时,Next.js 将自动回退到使用 Babel 来转换单个文件。这确保了与利用自定义 Babel 插件的现有应用程序的向后兼容性。
如果您正在使用自定义 Babel 设置,请分享您的配置。我们正在努力移植尽可能多的常用 Babel 转换,并将在未来支持插件。
| 版本 | 更改 |
|---|---|
v13.1.0 | Module Transpilation 和 Modularize Imports 稳定。 |
v13.0.0 | SWC 压缩器默认启用。 |
v12.3.0 | SWC 压缩器稳定版。 |
v12.2.0 | 添加了 SWC 插件的实验性支持。 |
v12.1.0 | 添加了对 Styled Components、Jest、Relay、移除 React 属性、传统装饰器、移除 Console 和 jsxImportSource 的支持。 |
v12.0.0 | Next.js 编译器推出。 |