Babel 的编译过程和自定义插件

const parser = require('@babel/parser');const traverse = require('@babel/traverse').default;const generator = require('@babel/generator').default;const sourceCode = `const a = 1;let b = 2;`;// 1. 解析源代码,生成 ASTconst ast = parser.parse(sourceCode);// 2. 遍历 AST,进行转换,通过访问者模式const visitor = {VariableDeclaration(path) {if (path.node.kind === 'const' || path.node.kind === 'let') {path.node.kind = 'var';}}}traverse(ast, visitor);// 3. 生成新的代码const { code } = generator(ast);console.log('源代码:', sourceCode);console.log('目标代码:', code);

const add = (a, b) => {return a + b}
const { types: t } = require('@babel/core')// babel 插件必须导出一个函数module.exports = exports = function () {// 通过访问者模式,访问 AST 中的节点,转换箭头函数为普通函数return {visitor: {ArrowFunctionExpression(path) {const node = path.node;// 箭头函数的 body 可能是一个表达式,也可能是一个块级语句const newBody = t.isBlockStatement(node.body) ?node.body : t.blockStatement([t.returnStatement(node.body)]);// 生成一个新的函数表达式,替换原来的箭头函数const functionExpression = t.functionExpression(null, // idnode.params, // paramsnewBody, // bodypath.node.generator, // generatorpath.node.async // async)// 替换原来的箭头函数path.replaceWith(functionExpression)}}}}

babel.config.json
{"plugins": ["./babelPlugins/my-arrow-func-plugin.js"]}
执行结果:


箭头函数 通过自定义 babel 插件 被编译为普通函数了。
夜雨聆风