ESTree Utility to Visit Nodes

2.0.0 · active · verified Sun Apr 19

estree-util-visit is a core utility within the unified (syntax-tree) ecosystem designed for traversing ESTree (and esast) abstract syntax trees. It enables developers to visit nodes in a depth-first traversal (preorder and/or postorder) for analysis or transformation. The current stable version is 2.0.0. The package distinguishes itself by duck-typing fields for node identification, eliminating the need for a predefined dictionary of node fields, which can simplify usage compared to other walkers. It provides symbolic controls (CONTINUE, EXIT, SKIP) for fine-grained traversal management. Releases are generally tied to ecosystem-wide updates or targeted feature enhancements. Since v2, it is an ESM-only package and requires Node.js 16 or newer.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing an ESTree with Acorn and then traversing it with `estree-util-visit` to find and log literal values, showcasing traversal control with `EXIT`.

import { parse } from 'acorn'
import { visit, CONTINUE, EXIT, SKIP } from 'estree-util-visit'

const tree = parse(
  'export function example() { const x = 1 + "2"; console.log(x); if (process.env.DEBUG === "true") { process.exit(3) } }',
  { sourceType: 'module', ecmaVersion: 2020 }
)

let literalsFound = 0;
visit(tree, function (node) {
  if (node.type === 'Literal' && 'value' in node) {
    console.log(`Found literal: ${JSON.stringify(node.value)}`);
    literalsFound++;
  }
  if (literalsFound >= 2) {
    console.log('Enough literals found, exiting traversal.');
    return EXIT;
  }
  return CONTINUE;
})

// Example of using enter/leave visitors
visit(tree, {
  enter(node) {
    // console.log(`Entering: ${node.type}`);
  },
  leave(node) {
    // console.log(`Leaving: ${node.type}`);
  }
});

view raw JSON →