Last change
on this file since 7deb3e2 was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago |
Initial commit
|
-
Property mode
set to
100644
|
File size:
1.6 KB
|
Line | |
---|
1 | # estree-walker
|
---|
2 |
|
---|
3 | Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn).
|
---|
4 |
|
---|
5 |
|
---|
6 | ## Installation
|
---|
7 |
|
---|
8 | ```bash
|
---|
9 | npm i estree-walker
|
---|
10 | ```
|
---|
11 |
|
---|
12 |
|
---|
13 | ## Usage
|
---|
14 |
|
---|
15 | ```js
|
---|
16 | var walk = require( 'estree-walker' ).walk;
|
---|
17 | var acorn = require( 'acorn' );
|
---|
18 |
|
---|
19 | ast = acorn.parse( sourceCode, options ); // https://github.com/acornjs/acorn
|
---|
20 |
|
---|
21 | walk( ast, {
|
---|
22 | enter: function ( node, parent, prop, index ) {
|
---|
23 | // some code happens
|
---|
24 | },
|
---|
25 | leave: function ( node, parent, prop, index ) {
|
---|
26 | // some code happens
|
---|
27 | }
|
---|
28 | });
|
---|
29 | ```
|
---|
30 |
|
---|
31 | Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called.
|
---|
32 |
|
---|
33 | Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one.
|
---|
34 |
|
---|
35 | Call `this.remove()` in either `enter` or `leave` to remove the current node.
|
---|
36 |
|
---|
37 | ## Why not use estraverse?
|
---|
38 |
|
---|
39 | The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.
|
---|
40 |
|
---|
41 | 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.)
|
---|
42 |
|
---|
43 | 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.
|
---|
44 |
|
---|
45 |
|
---|
46 | ## License
|
---|
47 |
|
---|
48 | MIT
|
---|
Note:
See
TracBrowser
for help on using the repository browser.