Babel's code transformations are enabled by applying plugins (or presets) to your configuration file.
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 an 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.
這些插件用于轉(zhuǎn)換你的代碼。
信息
轉(zhuǎn)換插件將啟用相應(yīng)的語法插件,因此你不必同時指定這兩種插件。
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.
NOTE: You don't need to specify the syntax plugin if the corresponding transform plugin is used already, since it enables it automatically.
或者,你也可以通過 Babel 解析器傳遞任何 plugins 參數(shù) :
Your .babelrc:
JSON
{
"parserOpts": {
"plugins": ["jsx", "flow"]
}
}
插件的排列順序很重要。
這意味著如果兩個轉(zhuǎn)換插件都將處理“程序(Program)”的某個代碼片段,則將根據(jù)轉(zhuǎn)換插件或 preset 的排列順序依次執(zhí)行。
例如:
babel.config.json
{
"plugins": ["transform-decorators-legacy", "transform-class-properties"]
}
先執(zhí)行 transform-decorators-legacy ,在執(zhí)行 transform-class-properties。
重要的時,preset 的順序是 顛倒的。如下設(shè)置:
babel.config.json
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
將按如下順序執(zhí)行: 首先是 @babel/preset-react,然后是 @babel/preset-env。
插件和 preset 都可以接受參數(shù),參數(shù)由插件名和參數(shù)對象組成一個數(shù)組,可以在配置文件中設(shè)置。
如果不指定參數(shù),下面這幾種形式都是一樣的:
babel.config.json
{
"plugins": ["pluginA", ["pluginA"], ["pluginA", {}]]
}
要指定參數(shù),請傳遞一個以參數(shù)名作為鍵(key)的對象。
babel.config.json
{
"plugins": [
[
"transform-async-to-module-method",
{
"module": "bluebird",
"method": "coroutine"
}
]
]
}
preset 的設(shè)置參數(shù)的工作原理完全相同:
babel.config.json
{
"presets": [
[
"env",
{
"loose": true,
"modules": false
}
]
]
}
請參考 babel-handbook 學(xué)習(xí)如何創(chuàng)建自己的插件。
一個簡單的用于反轉(zhuǎn)名稱順序的插件(來自于首頁):
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("");
},
},
};
}
更多建議: