实现一个简单的babel插件

babel的作用

babel先将代码编译为AST抽象语法树,修改AST,生成转换后的代码

生成AST抽象语法树

npm包

npm install babel-cli @babel/parser @babel/types @babel/traverse @babel/generator

  • babel命令:babel-cli
  • 编译器:@babel/parser
  • transform:
    • @babel/types 对AST进行增删改查
    • @babel/traverse 对AST进行遍历
  • generator:@babel/generator 生成转换后的代码

实例

编写一个插件将代码中的变量input转换为input1

目录结构

在这里插入图片描述

源码

example1/index.js文件:

let input = [1, 2, 3] 
input = input.map(item => item + 1) 
console.log(input)

编写插件

我们先去生成AST的网站看一下这段代码的语法树,我们发现input的类型是Identifier
在这里插入图片描述
在visitor中增加Identifier函数,所有AST节点类型是Identifier都会走进来,接下来我们就能改变原有的值啦。
example1/plugin.js文件:

module.exports = function(e) {
    return {
        name: 'example-1',
        visitor: {
            Identifier(path, state) {
                if(path.node.name === 'input') {
                    path.node.name = 'input1'
                }
            }
        }
    }
}

配置插件

.babelrc文件中加入自己编写的插件

{ 
	"plugins": [
        "./example1/plugin"
    ] 
}

进行编译

package.json文件中加入命令,指定转换后的文件输出到example1/compiled.js

"scripts": {
    "example1": "babel ./example1/index.js --out-file ./example1/compiled.js "
}

npm run example1运行命令后,我们发现example1/compiled.js中的代码已经将变量input转换为input1了:

let input1 = [1, 2, 3];
input1 = input1.map(item => item + 1);
console.log(input1);

版权声明:本文为qq_33721778原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。