babel的作用
babel先將代碼編譯為AST抽象語法樹,修改AST,生成轉(zhuǎn)換后的代碼
npm包
npm install babel-cli @babel/parser @babel/types @babel/traverse @babel/generator
babel命令:babel-cli
編譯器:@babel/parser
transform:
????????@babel/types 對(duì)AST進(jìn)行增刪改查
????????@babel/traverse 對(duì)AST進(jìn)行遍歷
generator:@babel/generator 生成轉(zhuǎn)換后的代碼
實(shí)例
編寫一個(gè)插件將代碼中的變量input轉(zhuǎn)換為input1
目錄結(jié)構(gòu)

源碼
example1/index.js文件:
let input = [1, 2, 3]
input = input.map(item => item + 1)
console.log(input)
編寫插件
我們先去生成AST的網(wǎng)站看一下這段代碼的語法樹,我們發(fā)現(xiàn)input的類型是Identifier

在visitor中增加Identifier函數(shù),所有AST節(jié)點(diǎn)類型是Identifier都會(huì)走進(jìn)來,接下來我們就能改變?cè)械闹道病?/p>
example1/plugin.js文件:
module.exports = function(e) {
? ? return {
? ? ? ? name: 'example-1',
? ? ? ? visitor: {
? ? ? ? ? ? Identifier(path, state) {
? ? ? ? ? ? ? ? if(path.node.name === 'input') {
? ? ? ? ? ? ? ? ? ? path.node.name = 'input1'
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
配置插件
在.babelrc文件中加入自己編寫的插件
{
"plugins": [
? ? ? ? "./example1/plugin"
? ? ]
}
進(jìn)行編譯
在package.json文件中加入命令,指定轉(zhuǎn)換后的文件輸出到example1/compiled.js
"scripts": {
? ? "example1": "babel ./example1/index.js --out-file ./example1/compiled.js "
}
npm run example1運(yùn)行命令后,我們發(fā)現(xiàn)example1/compiled.js中的代碼已經(jīng)將變量input轉(zhuǎn)換為input1了:
let input1 = [1, 2, 3];
input1 = input1.map(item => item + 1);
console.log(input1);