babel conversion function arrow

Before the conversion:

const sum = (a,b)=>a+b

 

 

After the conversion:

// "use strict";

// var fn = function fn(a, b) {
// return a + b;
// };
 
 

 

 

 

 

achieve:

From the comparison of the picture we can see that the biggest difference is in the init, different functions

init
Es6 : ArrowFunctionExpression
Es5: FunctionExpression
 
 
So we can use a plug-in conversion
 
let t = require('@babel/types');
 
 
specific:
const babel = require('@babel/core');
let   code = `let  fn = (a,b) => a + b`;
let   t = require('@babel/types');
//1.init   
//    Es6 : ArrowFunctionExpression  
//    Es5:  FunctionExpression
/// t.functionExpression(id, params, body, generator, async) 
// id: Identifier (default: null)
// params: Array<LVal> (required)
// body: BlockStatement (required)
// generator: boolean (default: false)
// async: boolean (default: false)
// returnType: TypeAnnotation | TSTypeAnnotation | Noop (default: null)
// typeParameters: TypeParameterDeclaration | TSTypeParameterDeclaration | Noop (default: null)



//2. body 
//  
//  ES5   BlockStatement
//  Es6   ExpressionStatement
let transformArrowFunctions = {
    visitor: {
        ArrowFunctionExpression: (path, state) => {
            // console.log(path.node)
            // console.log(path.parent.id)
            let node = path.node;
            let id = path.parent.id;
            let params = node.params;
            let body=t.blockStatement([
                t.returnStatement(node.body)
            ]);
            //将ArrowFunctionExpression  转化为  FunctionExpression ,传入不要的参数
            let functionExpression = t.functionExpression(id,params,body,false,false);
            path.replaceWith(functionExpression);
        }
    }
}
const result = babel.transform(code, {
    plugins: [transformArrowFunctions]
});
console.log(result.code);

// let fn = function fn(a, b) {
//     return a + b;
//   };
  

Output:

let fn = function fn(a, b) {
  return a + b;
};

AST tree visualization tools Web site: https://astexplorer.net/  

Guess you like

Origin www.cnblogs.com/guangzhou11/p/11441146.html