Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

estree-walker

Rich-Harris103.7mMIT3.0.3TypeScript support: included

Traverse an ESTree-compliant AST

readme

estree-walker

Simple utility for walking an ESTree-compliant AST, such as one generated by acorn.

Installation

npm i estree-walker

Usage

var walk = require('estree-walker').walk;
var acorn = require('acorn');

ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn

walk(ast, {
  enter(node, parent, prop, index) {
    // some code happens
  },
  leave(node, parent, prop, index) {
    // some code happens
  }
});

Inside the enter function, calling this.skip() will prevent the node's children being walked, or the leave function (which is optional) being called.

Call this.replace(new_node) in either enter or leave to replace the current node with a new one.

Call this.remove() in either enter or leave to remove the current node.

Why not use estraverse?

The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where estraverse was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.

estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.)

None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful.

License

MIT

changelog

changelog

3.0.3

  • Add dependencies on @types/estree (#34)
  • Internal refactoring (#34)

3.0.2

  • Add types to exports

3.0.1

  • Add package.json to exports

3.0.0

  • Remove CommonJS vestiges

2.0.2

  • Internal tidying up (change test runner, convert to JS)

2.0.1

  • Robustify this.remove(), pass current index to walker functions (#18)

2.0.0

  • Add an asyncWalk export (#20)
  • Internal rewrite

1.0.1

  • Relax node type to BaseNode (#17)

1.0.0

  • Don't cache child keys

0.9.0

  • Add this.remove() method

0.8.1

  • Fix pkg.files

0.8.0

  • Adopt estree types

0.7.0

  • Add a this.replace(node) method

0.6.1

  • Only traverse nodes that exist and have a type (#9)
  • Only cache keys for nodes with a type (#8)

0.6.0

  • Fix walker context type
  • Update deps, remove unncessary Bublé transformation

0.5.2

  • Add types to package

0.5.1

  • Prevent context corruption when walk() is called during a walk

0.5.0

  • Export childKeys, for manually fixing in case of malformed ASTs

0.4.0

  • Add TypeScript typings (#3)

0.3.1

  • Include pkg.repository (#2)

0.3.0

  • More predictable ordering

0.2.1

  • Keep context shape

0.2.0

  • Add ES6 build

0.1.3

  • npm snafu

0.1.2

  • Pass current prop and index to enter/leave callbacks

0.1.1

  • First release