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) => { });