The installation
$ npm install --save @babel/traverse
Copy the code
use
We can use it with the Babel parser to traverse and update nodes:
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"; }}});Copy the code
In addition, we can target specific node types in the syntax tree
traverse(ast, { FunctionDeclaration: function(path) { path.node.id.name = "x"; }})Copy the code
: Book: Read the full document here