W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
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)換插件將啟用相應的語法插件,因此你不必同時指定這兩種插件。
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 的順序是 顛倒的。如下設置:
babel.config.json
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
將按如下順序執(zhí)行: 首先是 @babel/preset-react,然后是 @babel/preset-env。
插件和 preset 都可以接受參數(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ù)的工作原理完全相同:
babel.config.json
{
"presets": [
[
"env",
{
"loose": true,
"modules": false
}
]
]
}
請參考 babel-handbook 學習如何創(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("");
},
},
};
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: