2020-07-23 babel ast遍历

2020-07-23  本文已影响0人  FConfidence

babel

# 安装依赖
npm install @babel/core @babel/types --save-dev
// babel核心库, 用来实现核心的转换引擎
const babel = require('@babel/core');

// let babelTypes = require('@babel/types');
export default function () {
  const { types: babelTypes } = babel;
  
  return {
    name: "ast-transform", // not required
    visitor: {
      // babel内部会先把代码转成ast, 然后再进行遍历 (匹配type)
      ArrowFunctionExpression: (path) => {
        let node = path.node;
        let id = path.parent.id;
        let params = node.params;
        // 创建一个body
        const body = babelTypes.blockStatement([babelTypes.returnStatement(node.body)]);
        // 生成一个函数
        let functionExpression = babelTypes.functionExpression(id, params, body, false, false);
        // 用新的函数替换老的函数
        path.replaceWith(functionExpression);
      },
    }
  };
}

测试

const arrowFuncCode = `const sum = (a,b) => a + b`;

const transformArrowFunctions  = require('./transformArrowFunctions.js');
const arrowResult = babel.transform(arrowFuncCode, {
  plugins: [transformArrowFunctions],
});

console.log(arrowResult.code);
/*
const sum = function sum(a, b) {
  return a + b;
};
*/
上一篇下一篇

猜你喜欢

热点阅读