const recast = require("recast");
const {variableDeclaration, variableDeclarator, functionExpression} = recast.types.builders
const code = `
function add(a, b) {
return a +
// 有什么奇怪的东西混进来了
b
}`
const ast = recast.parse(code);
const add = ast.program.body[0]
ast.program.body[0] = variableDeclaration("const", [
variableDeclarator(add.id, functionExpression(
null, // Anonymize the function expression.
add.params,
add.body
))
]);
//将AST对象重新转回可以阅读的代码
const output = recast.print(ast).code;
console.log(output)