题目:将 var a = 3; 通过AST替换成 var a = 1+2;
本次所用到的知识
1.path.replaceWith
(单)节点替换函数,调用方式
path.replaceWith(newNode);
实参一般是node类型,即将当前遍历的path替换为实参里的新节点
注意,它不能用于Array的替换,即实参不能是Array的类型
2.babel/types
const types = require("@babel/types");
它的功能非常强大,操作AST,主要是对节点进行替换,删除,增加等操作
3.AST代码
const {parse} = require("@babel/parser");
const generator = require("@babel/generator").default;
const t = require("@babel/types");
const traverse = require("@babel/traverse").default;
js_code = `var a = 3;`
ast = parse(js_code)
traverse(ast,{Literal(path){if (path.node.value === 3){const left = t.numericLiteral(1);const right = t.numericLiteral(2);const BinaryExp = t.BinaryExpression("+",left,right);// 替换掉原来的字面量path.replaceWith(BinaryExp)}}
})
const { code } = generator(ast,{},js_code);
console.log(code);
若不使用babel/types也可以实现,代码如下
const { parse } = require("@babel/parser");
const generator = require("@babel/generator").default;
const t = require("@babel/types");
const traverse = require("@babel/traverse").default;js_code = `var a = 3;`
ast = parse(js_code)
traverse(ast,{Literal(path){if (path.node.value===3){// console.log(path.node.value)// const left = t.numericLiteral(1);// const right = t.numericLiteral(2);// const binaryExp = t.binaryExpression("+",left,right)const binaryExp2 = {type: "BinaryExpression",operator:"+",left:{type:"NumericLiteral",value:1},right:{type:"NumericLiteral",value:2},}path.replaceWith(binaryExp2)};}
})
const {code} = generator(ast);
console.log(code)