@babel/traverse

Install

  1. npm install --save @babel/traverse

Usage

We can use it alongside the babel parser to traverse and update nodes:

  1. import * as parser from "@babel/parser";
  2. import traverse from "@babel/traverse";
  3. const code = `function square(n) {
  4. return n * n;
  5. }`;
  6. const ast = parser.parse(code);
  7. traverse(ast, {
  8. enter(path) {
  9. if (path.isIdentifier({ name: "n" })) {
  10. path.node.name = "x";
  11. }
  12. },
  13. });

Also, we can target particular node types in the Syntax Tree

  1. traverse(ast, {
  2. FunctionDeclaration: function(path) {
  3. path.node.id.name = "x";
  4. },
  5. });

📖 Read the full docs here