Babel
Examples
Next.js 包含应用的 next/babel
预设,其中包括编译 React 应用和服务器端代码所需的所有内容。但如果你想扩展默认的 Babel 配置,也是可以的。
¥Next.js includes the next/babel
preset to your app, which includes everything needed to compile React applications and server-side code. But if you want to extend the default Babel configs, it's also possible.
添加预设和插件
¥Adding Presets and Plugins
首先,你只需在项目的根目录中定义一个 .babelrc
文件(或 babel.config.js
)。如果找到这样的文件,它将被视为事实来源,因此它还需要定义 Next.js 需要的内容,即 next/babel
预设。
¥To start, you only need to define a .babelrc
file (or babel.config.js
) in the root directory of your project. If such a file is found, it will be considered as the source of truth, and therefore it needs to define what Next.js needs as well, which is the next/babel
preset.
这是 .babelrc
文件的示例:
¥Here's an example .babelrc
file:
{
"presets": ["next/babel"],
"plugins": []
}
你可以通过 看看这个文件 了解 next/babel
包含的预设。
¥You can take a look at this file to learn about the presets included by next/babel
.
要添加预设/插件而不配置它们,你可以这样做:
¥To add presets/plugins without configuring them, you can do it this way:
{
"presets": ["next/babel"],
"plugins": ["@babel/plugin-proposal-do-expressions"]
}
自定义预设和插件
¥Customizing Presets and Plugins
要添加具有自定义配置的预设/插件,请在 next/babel
预设上执行此操作,如下所示:
¥To add presets/plugins with custom configuration, do it on the next/babel
preset like so:
{
"presets": [
[
"next/babel",
{
"preset-env": {},
"transform-runtime": {},
"styled-jsx": {},
"class-properties": {}
}
]
],
"plugins": []
}
要了解有关每个配置的可用选项的更多信息,请访问 babel 的 documentation 站点。
¥To learn more about the available options for each config, visit babel's documentation site.
很高兴知道:
¥Good to know:
Next.js 使用 当前 Node.js 版本 进行服务器端编译。
¥Next.js uses the current Node.js version for server-side compilations.
"preset-env"
上的modules
选项应保留为false
,否则 webpack 代码分割将被关闭。¥The
modules
option on"preset-env"
should be kept tofalse
, otherwise webpack code splitting is turned off.