简介

Babel 编译的三个阶段
Babel 的编译过程和大多数其他语言的编译器相似,可以分为三个阶段:

  • 解析(Parsing):将代码字符串解析成抽象语法树。
  • 转换(Transformation):对抽象语法树进行转换操作。
  • 生成(Code Generation): 根据变换后的抽象语法树再生成代码字符串。

开始

写一个把所有定义变量名为 a 的换成b的简单的插件
我们可以从这里得到 example link var a = 1的抽象语法树

{
  "type": "Program",
  "start": 0,
  "end": 9,
  "body": [
    {
      "type": "VariableDeclaration",
      "start": 0,
      "end": 9,
      "declarations": [
        {
          "type": "VariableDeclarator",
          "start": 4,
          "end": 9,
          "id": {
            "type": "Identifier",
            "start": 4,
            "end": 5,
            "name": "a"
          },
          "init": {
            "type": "Identifier",
            "start": 8,
            "end": 9,
            "name": "b"
          }
        }
      ],
      "kind": "var"
    }
  ],
  "sourceType": "module"
}

index.js

import * as babel from '@babel/core';
const c = `var a = 1`;
const { code } = babel.transform(c, {
    plugins: [
        function ({ types: t }) {
            return {
                visitor: {
                    VariableDeclarator(path, state) {
                        if (path.node.id.name == 'a') {
                            path.node.id = t.identifier('b')
                        }
                    }
                }
            }
        }
    ]
})

console.log(code); // var b = 1