實(shí)現(xiàn)一個(gè)簡(jiǎn)單的babel插件

babel的作用

babel先將代碼編譯為AST抽象語法樹,修改AST,生成轉(zhuǎn)換后的代碼

生成AST抽象語法樹

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);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容