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

带你入门前端
38 声望2 粉丝

通俗易懂,言简意赅授课