babel-core babel-types转换箭头函数
let add = (a,b)=>a+b; 转换前
// 转换后
let add = function (a, b) {
return a + b;
};
需要用到的包:babel-core
babel-types
npm i babel-core babel-types -D
相关包的作用
babel-core:babel核心库,用来实现核心的转换
babel-types:用来类型判断,生成AST节点
代码如下
let babel = require("babel-core");
let types = require("babel-types");
let str = `let add = (a,b)=>a+b`; // let sum = function (a,b){return a+b}
let plugin = {
visitor: { // 固定写法,对应ArrowFunctionExpression
ArrowFunctionExpression(path) {
let node = path.node; // 父节点
let params = node.params;
let block = types.blockStatement([
types.returnStatement(node.body),
]);
let func = types.functionExpression(
null,
params,
block,
false,
false
); // 生成es5函数
path.replaceWith(func);
},
},
};
// babel先将代码转成AST,然后遍历,
let result = babel.transform(str, {
plugins: [plugin],
});
console.log(result.code);
打印结果:
let add = function (a, b) {
return a + b;
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。