let obj = {
name: 'lanqian',
add: function(a, b){
return a + b + 1000;
},
mul: function(a, b){
return a * b + 1000;
}
}
const fs = require('fs');
const parser = require("E:/nodejs/npm_global_modules/node_modules/@babel/parser")
const traverse = require("E:/nodejs/npm_global_modules/node_modules/@babel/traverse").default
const t = require("E:/nodejs/npm_global_modules/node_modules/@babel/types")
const generator = require("E:/nodejs/npm_global_modules/node_modules/@babel/generator").default
const jscode = fs.readFileSync("./demo.js", {encoding: "utf-8"});
let ast = parser.parse(jscode)
//ast操作
// let code = generator(ast).code
// console.log(ast)
//遍历节点,替换参数
const updateParamNameVisitor = {
Identifier(path){
if (path.node.name == this.paramName){
path.node.name = "x"
}
}
}
const visitor = {
FunctionExpression(path){
const paramName = path.node.params[0].name;
path.traverse(updateParamNameVisitor, {
paramName
});
}
}
traverse(ast, visitor)
//语法树转成代码
let code = generator(ast).code
console.log(code)
// fs.writeFile('./demoNew.js', code, (err) =>{})
网友评论