//@Author : dingjiawen //@Date : 2024/03/25 15:26 //@Usage : //@Desc :使用AST技术,还原code1.js import {traverse, types} from "@babel/core"; import {parse} from "@babel/parser"; import CodeGenerator from "@babel/generator"; // import * as types from "@babel/types"; import fs from "fs"; const code = fs.readFileSync("code/code3.js", "utf-8"); let ast = parse(code) traverse(ast, { IfStatement(path) { let {consequent, alternate} = path.node; let testpath = path.get("test"); const evaluateTest = testpath.evaluateTruthy(); if (evaluateTest === true) { if (types.isBlockStatement(consequent)) { consequent = consequent.body; } path.replaceWithMultiple(consequent); } else if (evaluateTest === false) { if (alternate != null) { if (types.isBlockStatement(alternate)) { alternate = alternate.body; } path.replaceWithMultiple(alternate); } else { path.remove(); } } }, }); const {code: output} = CodeGenerator.default(ast); console.log(output)