使用一個AST庫做babel插件轉(zhuǎn)化步驟
- 打開網(wǎng)頁https://astexplorer.net/, 可以選擇esprima作為AST解析庫,可以輸入代碼
const sum = (a,b) => a+b;
,截圖如下,好吧右邊就是解析好的AST的語法樹了, 可以仔細(xì)看下每段代碼都有對應(yīng)的屬性描述
image.png
JS中引用babel相應(yīng)的包,可以實(shí)現(xiàn)把代碼輸入進(jìn)去,在解析間通過訪問者模式,你可以聲明不同類型(對應(yīng)解析為AST語法樹的type類型)的訪問者,當(dāng)作插件注入到轉(zhuǎn)換的過程中
在解析期間會傳入解析的節(jié)點(diǎn),你需要做的就是處理這些節(jié)點(diǎn)的類型或者值,替換為你需要的東西,這樣一個AST的babel插件就寫好了,下面事簡單的代碼
const babel = require("@babel/core");
const babelTypes = require("babel-types");
// 箭頭函數(shù)代碼
const code = "const sum = (a,b) => a+b";
// 寫自己的babel的轉(zhuǎn)換器,visitor的訪問者模式
let transformArrowFunction = {
visitor: { // 訪問者模式, 處理箭頭函數(shù)
ArrowFunctionExpression: (path,state) => {
let node = path.node;
let id = path.parent.id;
let params = node.params;
// 創(chuàng)建大括號表達(dá)式
let body = babelTypes.blockStatement([
babelTypes.returnStatement(node.body)
]);
// 創(chuàng)建函數(shù)表達(dá)式
let functionExpression = babelTypes.functionExpression(id,params,body,false,false);
// 把原來的箭頭表達(dá)式替換了
path.replaceWith(functionExpression);
}
}
};
// 用babel的轉(zhuǎn)換,傳個插件進(jìn)去
const result = babel.transform(code,{
plugins: [
transformArrowFunction
]
});
console.log(code);
console.log(result.code);