跳到主要内容

预设(Presets)

Babel 的预设(preset)可以被看作是一组 Babel 插件和/或 options 配置的可共享模块。

官方提供的预设

我们已经针对常用环境编写了一些预设(preset):

Other Integrations

If you aren't using Babel directly, the framework you are using may have its own configuration for you to use or extend. Many other community maintained presets are available on npm!

Next.js | Nuxt.js | Parcel | Jest | Gatsby

Using a Preset

Within a Babel config, if the preset is on npm, you can pass in the name of the preset and Babel will check that it's installed in node_modules already. This is added to the presets config option, which takes an array.

babel.config.json
{
"presets": ["babel-preset-myPreset", "@babel/preset-env"]
}

Otherwise, you can also specify a relative or absolute path to your presets.

babel.config.json
{
"presets": ["./myProject/myPreset"]
}

See name normalization for more specifics on configuring the path of a plugin or preset.

Stage-X(实验性质的预设)

Deprecated

As of Babel 7, we've decided to deprecate the Stage-X presets and stop publishing them. Because these proposals are inherently subject to change, it seems better to ask users to specify individual proposals as plugins vs. a catch all preset that you would need to check up on anyway. Check out our blog for more context.

Any transforms in stage-x presets are changes to the language that haven't been approved to be part of a release of JavaScript (such as ES6/ES2015).

TC39 将提案分为以下几个阶段:

  • Stage 0 - 设想(Strawman):只是一个想法,可能有 Babel插件。
  • Stage 1 - 建议(Proposal):这是值得跟进的。
  • Stage 2 - 草案(Draft):初始规范。
  • Stage 3 - 候选(Candidate):完成规范并在浏览器上初步实现。
  • Stage 4 - 完成(Finished):将添加到下一个年度版本发布中。

有关详细信息,请务必查看 current TC39 proposals 及其 process document

TC39 各阶段的流程也在一些文章中有详细的解释,在 Yehuda Katz (@wycatz) 的 thefeedbackloop.xyz网站上:Stage 0 and 1Stage 2Stage 3

创建预设

如需创建一个自己的预设(无论是为了本地使用还是发布到 npm),需要导出(export)一个配置对象。

可以是返回一个插件数组...

JavaScript
module.exports = function() {
return {
plugins: ["pluginA", "pluginB", "pluginC"],
};
};

preset 可以包含其他的 preset,以及带有参数的插件。

JavaScript
module.exports = () => ({
presets: [require("@babel/preset-env")],
plugins: [
[require("@babel/plugin-transform-class-properties"), { loose: true }],
require("@babel/plugin-transform-object-rest-spread"),
],
});

有关更多信息,请参考 babel 手册 中关于 preset 的部分。

预设的排列顺序

Preset 是逆序排列的(从后往前)。

babel.config.json
{
"presets": ["a", "b", "c"]
}

将按如下顺序执行: cb 然后是 a

这主要是为了确保向后兼容,由于大多数用户将 "es2015" 放在 "stage-0" 之前。

预设的参数

插件和 preset 都可以接受参数,参数由插件名和参数对象组成一个数组,可以在配置文件中设置。

如果不指定参数,下面这几种形式都是一样的:

babel.config.json
{
"presets": [
"presetA", // bare string
["presetA"], // wrapped in array
["presetA", {}] // 2nd argument is an empty options object
]
}

要指定参数,请传递一个以参数名作为键(key)的对象。

babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"loose": true,
"modules": false
}
]
]
}