UNPKG

2.75 kBMarkdownView Raw
1# falafel
2
3Transform the [ast](http://en.wikipedia.org/wiki/Abstract_syntax_tree) on a
4recursive walk.
5
6[![build status](https://secure.travis-ci.org/substack/node-falafel.png)](http://travis-ci.org/substack/node-falafel)
7
8This module is like [burrito](https://github.com/substack/node-burrito),
9except that it uses [esprima](http://esprima.org) instead of
10[uglify](https://github.com/mishoo/UglifyJS)
11for friendlier-looking ast nodes.
12
13# example
14
15## array.js
16
17Put a function wrapper around all array literals.
18
19``` js
20var falafel = require('falafel');
21
22var src = '(' + function () {
23 var xs = [ 1, 2, [ 3, 4 ] ];
24 var ys = [ 5, 6 ];
25 console.dir([ xs, ys ]);
26} + ')()';
27
28var output = falafel(src, function (node) {
29 if (node.type === 'ArrayExpression') {
30 node.update('fn(' + node.source() + ')');
31 }
32});
33console.log(output);
34```
35
36output:
37
38```
39(function () {
40 var xs = fn([ 1, 2, fn([ 3, 4 ]) ]);
41 var ys = fn([ 5, 6 ]);
42 console.dir(fn([ xs, ys ]));
43})()
44```
45
46# methods
47
48``` js
49var falafel = require('falafel')
50```
51
52## falafel(src, opts={}, fn)
53
54Transform the string source `src` with the function `fn`, returning a
55string-like transformed output object.
56
57For every node in the ast, `fn(node)` fires. The recursive walk is a
58pre-traversal, so children get called before their parents.
59
60Performing a pre-traversal makes it easier to write nested transforms since
61transforming parents often requires transforming all its children first.
62
63The return value is string-like (it defines `.toString()` and `.inspect()`) so
64that you can call `node.update()` asynchronously after the function has
65returned and still capture the output.
66
67Instead of passing a `src` you can also use `opts.source`.
68
69All of the `opts` will be passed directly to esprima except for `'range'` which
70is always turned on because falafel needs it.
71
72Some of the options you might want from esprima includes:
73`'loc'`, `'raw'`, `'comments'`, `'tokens'`, and `'tolerant'`.
74
75# nodes
76
77Aside from the regular [esprima](http://esprima.org) data, you can also call
78some inserted methods on nodes.
79
80Aside from updating the current node, you can also reach into sub-nodes to call
81update functions on children from parent nodes.
82
83## node.source()
84
85Return the source for the given node, including any modifications made to
86children nodes.
87
88## node.update(s)
89
90Transform the source for the present node to the string `s`.
91
92Note that in `'ForStatement'` node types, there is an existing subnode called
93`update`. For those nodes all the properties are copied over onto the
94`node.update()` function.
95
96## node.parent
97
98Reference to the parent element or `null` at the root element.
99
100# install
101
102With [npm](http://npmjs.org) do:
103
104```
105npm install falafel
106```
107
108# license
109
110MIT