跳到主要内容

插件

Babel's code transformations are enabled by applying plugins (or presets) to your configuration file.

Using a Plugin

If the plugin is on npm, you can pass in the name of the plugin and Babel will check that it's installed in node_modules. This is added to the plugins config option, which takes an array.

babel.config.json
{
"plugins": ["babel-plugin-myPlugin", "@babel/plugin-transform-runtime"]
}

You can also specify a relative/absolute path to your plugin.

babel.config.json
{
"plugins": ["./node_modules/asdf/plugin"]
}

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

转换插件

这些插件用于转换你的代码。

信息

转换插件将启用相应的语法插件,因此你不必同时指定这两种插件。

语法插件

Most syntax is transformable by Babel. In rarer cases (if the transform isn't implemented yet, or there isn't a default way to do so), you can use plugins such as @babel/plugin-syntax-bigint to only allow Babel to parse specific types of syntax. Or you want to preserve the source code because you only want Babel to do code analysis or codemods.

提示

You don't need to specify the syntax plugin if the corresponding transform plugin is used already, since it enables it automatically.

或者,你也可以通过 Babel 解析器传递任何 plugins 参数

Your .babelrc:

JSON
{
"parserOpts": {
"plugins": ["jsx", "flow"]
}
}

插件顺序

插件的排列顺序很重要。

这意味着如果两个转换插件都将处理“程序(Program)”的某个代码片段,则将根据转换插件或 preset 的排列顺序依次执行。

  • 插件在 Presets 前运行。
  • 插件顺序从前往后排列。
  • Preset 顺序是颠倒的(从后往前)。

例如:

babel.config.json
{
"plugins": ["transform-decorators-legacy", "transform-class-properties"]
}

先执行 transform-decorators-legacy ,在执行 transform-class-properties

重要的时,preset 的顺序是 颠倒的。如下设置:

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

将按如下顺序执行: 首先是 @babel/preset-react,然后是 @babel/preset-env

插件参数

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

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

babel.config.json
{
"plugins": ["pluginA", ["pluginA"], ["pluginA", {}]]
}

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

babel.config.json
{
"plugins": [
[
"transform-async-to-module-method",
{
"module": "bluebird",
"method": "coroutine"
}
]
]
}

preset 的设置参数的工作原理完全相同:

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

插件开发

请参考 babel-handbook 学习如何创建自己的插件。

一个简单的用于反转名称顺序的插件(来自于首页):

JavaScript
export default function() {
return {
visitor: {
Identifier(path) {
const name = path.node.name;
// reverse the name: JavaScript -> tpircSavaJ
path.node.name = name
.split("")
.reverse()
.join("");
},
},
};
}