Skip to content

Latest commit

 

History

History
45 lines (34 loc) · 906 Bytes

traverse.md

File metadata and controls

45 lines (34 loc) · 906 Bytes
id title
babel-traverse
@babel/traverse

Install

npm install --save @babel/traverse

Usage

We can use it alongside 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";
    }
  },
});

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

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

📖 Read the full docs here