我们可以将它与 babel 解析器一起使用来遍历和更新节点:

import * as parser from "@babel/parser";
import traverse from "@babel/traverse";
 
const code = `function square(n) {
  return n * n;
}`;
 
const ast = parser.parse(code);
 
traverse(ast, {
  enter(path) {
    if (path.isIdentifier({ name: "n" })) {
      path.node.name = "x";
    }
  },
});

此外,我们可以在 Syntax Tree 中定位特定的节点类型

traverse(ast, {
  FunctionDeclaration: function(path) {
    path.node.id.name = "x";
  },
});