ast babeljs --2( 数组替换)
作者:互联网
https://www.cnblogs.com/gaoyongjian/p/13246736.html
// 将js代码转换成AST const { parse } = require("@babel/parser"); // 用来遍历AST中的节点 const traverse = require("@babel/traverse").default; // AST转换成js const generator = require("@babel/generator").default; // 用来判断节点类型和生成新的节点 const t = require("@babel/types"); const fs = require("fs"); const jscode = fs.readFileSync("./demo.js", { encoding: "utf-8" }); let ast = parse(jscode); //some function code const visitor = { VariableDeclarator(path) { // 还原数组对象 const { id, init } = path.node; // 非Array或者没有元素, 返回 if (!t.isArrayExpression(init) || init.elements.length === 0) return; let elements = init.elements; // 获取binding实例 const binding = path.scope.getBinding(id.name); for (const ref_path of binding.referencePaths) { // 获取 MemberExpression 父节点 let member_path = ref_path.findParent(p => p.isMemberExpression()); if (member_path == null) continue; let property = member_path.get('property'); // 索引值不是 NumericLiteral 类型的不处理 if (!property.isNumericLiteral()) { continue; } // 获取索引值 let index = property.node.value; // 获取索引值对应的节点, 并替换 let arr_ele = elements[index]; member_path.replaceWith(arr_ele) } } } traverse(ast, visitor); let code = generator(ast).code; fs.writeFile('./demoNew.js', code, (err) => { });
标签:code,const,ast,--,require,init,let,path,babeljs 来源: https://www.cnblogs.com/angdh/p/14405766.html