babel 转换箭头函数
生活随笔
收集整理的這篇文章主要介紹了
babel 转换箭头函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉換前:
const sum = (a,b)=>a+b
?
?
轉化后:
// "use strict";// var fn = function fn(a, b) { // return a + b; // };
?
?
?
?
實現:
從圖片的對比我們可以看出最大的不同是在 init 時,函數的不同
init Es6 : ArrowFunctionExpression Es5: FunctionExpression 所以我們可以利用一個插件轉化 let t = require('@babel/types'); 具體: 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; // };輸出:
let fn = function fn(a, b) {return a + b; };AST樹可視化工具的網站:? https://astexplorer.net/??
轉載于:https://www.cnblogs.com/guangzhou11/p/11441146.html
總結
以上是生活随笔為你收集整理的babel 转换箭头函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MacOS常用快捷键
- 下一篇: Spring事务处理流程和原理(动脑学院