const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
// 将js代码转换成AST
// const { parse } = require("@babel/parser");
// 用来遍历AST中的节点
// const traverse = require("@babel/traverse").default;
// AST转换成js
const generator = require("@babel/generator").default;
// 用来判断节点类型和生成新的节点
const types = require("@babel/types");
const jscode = `
var a = [1,2,3,[1213,234],{"code":"666"},window];
b = a[1] + a[2] + a[3];
c = a[4];
d = a[5];
`;
let ast = parser.parse(jscode);
const replaceArrayElements =
{//数组还原
VariableDeclarator(path) {
let { node, scope } = path;
let { id, init } = node;
if (!types.isArrayExpression(init)) return;
const binding = scope.getBinding(id.name);
if (!binding || !binding.constant) {
return;
}
for (let referPath of binding.referencePaths) {
let { node, parent } = referPath;
if (!types.isMemberExpression(parent, { object: node }) || !types.isNumericLiteral(parent.property)) {
return;
};
}
for (let referPath of binding.referencePaths) {
let { parent, parentPath } = referPath;
let index = parent.property.value;
parentPath.replaceWith(init.elements[index]);
}
path.remove();
},
}
traverse(ast, replaceArrayElements);
let { code } = generator(ast);
console.log(code);