What is falafel?
The 'falafel' npm package is a tool for parsing and transforming JavaScript code. It allows you to traverse and manipulate the abstract syntax tree (AST) of JavaScript code, making it useful for tasks such as code analysis, transformation, and instrumentation.
What are falafel's main functionalities?
Parsing JavaScript Code
This feature allows you to parse JavaScript code into an AST and traverse it. In this example, the code parses a simple JavaScript snippet and logs the type of each node in the AST.
const falafel = require('falafel');
const src = 'let x = 5;';
falafel(src, function (node) {
console.log(node.type);
});
Transforming JavaScript Code
This feature allows you to transform JavaScript code by modifying the AST. In this example, the code changes the variable declaration from 'x' to 'y' and updates its value.
const falafel = require('falafel');
const src = 'let x = 5;';
const output = falafel(src, function (node) {
if (node.type === 'VariableDeclarator' && node.id.name === 'x') {
node.update('y = 10');
}
});
console.log(output.toString());
Code Instrumentation
This feature allows you to instrument JavaScript code by injecting additional code into the AST. In this example, the code adds a console log before each return statement.
const falafel = require('falafel');
const src = 'function add(a, b) { return a + b; }';
const output = falafel(src, function (node) {
if (node.type === 'ReturnStatement') {
node.update('console.log("Returning: ", ' + node.argument.source() + '); ' + node.source());
}
});
console.log(output.toString());
Other packages similar to falafel
esprima
Esprima is a high-performance, standard-compliant ECMAScript parser. It parses JavaScript code into an AST, similar to falafel, but does not provide transformation capabilities out of the box. It is often used in conjunction with other tools for code analysis and transformation.
babel
Babel is a popular JavaScript compiler that allows you to use next-generation JavaScript, today. It provides extensive capabilities for parsing, transforming, and generating JavaScript code. Compared to falafel, Babel offers a more comprehensive set of features and plugins for code transformation and transpilation.
acorn
Acorn is a small, fast, JavaScript-based JavaScript parser. It generates an AST from JavaScript code, similar to falafel. While it is highly performant and minimalistic, it does not include built-in transformation capabilities, making it more suitable for parsing and analysis tasks.
falafel
Transform the ast on a
recursive walk.
This module is like burrito,
except that it uses esprima instead of
uglify
for friendlier-looking ast nodes.
example
array.js
Put a function wrapper around all array literals.
var falafel = require('falafel');
var src = '(' + function () {
var xs = [ 1, 2, [ 3, 4 ] ];
var ys = [ 5, 6 ];
console.dir([ xs, ys ]);
} + ')()';
var output = falafel(src, function (node) {
if (node.type === 'ArrayExpression') {
node.update('fn(' + node.source() + ')');
}
});
console.log(output);
output:
(function () {
var xs = fn([ 1, 2, fn([ 3, 4 ]) ]);
var ys = fn([ 5, 6 ]);
console.dir(fn([ xs, ys ]));
})()
custom keyword
Creating custom keywords is super simple!
This example creates a new beep
keyword that uppercases its arguments:
var falafel = require('falafel');
var src = 'console.log(beep "boop", "BOOP");';
function isKeyword (id) {
if (id === 'beep') return true;
}
var output = falafel(src, { isKeyword: isKeyword }, function (node) {
if (node.type === 'UnaryExpression'
&& node.keyword === 'beep') {
node.update(
'String(' + node.argument.source() + ').toUpperCase()'
);
}
});
console.log(output);
Now the source string console.log(beep "boop", "BOOP");
is converted to:
$ node example/keyword.js
console.log(String("boop").toUpperCase(), "BOOP");
which we can execute:
$ node example/keyword.js | node
BOOP BOOP
Neat!
methods
var falafel = require('falafel')
falafel(src, opts={}, fn)
Transform the string source src
with the function fn
, returning a
string-like transformed output object.
For every node in the ast, fn(node)
fires. The recursive walk is a
pre-traversal, so children get called before their parents.
Performing a pre-traversal makes it easier to write nested transforms since
transforming parents often requires transforming all its children first.
The return value is string-like (it defines .toString()
and .inspect()
) so
that you can call node.update()
asynchronously after the function has
returned and still capture the output.
Instead of passing a src
you can also use opts.source
.
All of the opts
will be passed directly to esprima except for 'range'
which
is always turned on because falafel needs it.
Some of the options you might want from esprima includes:
'loc'
, 'raw'
, 'comments'
, 'tokens'
, and 'tolerant'
.
falafel uses a custom patch of esprima with support for an opts.isKeyword()
function. When opts.isKeyword(id)
returns true
, the string id
will be
treated as a keyword. You can use this behavior to create custom unary
expression keywords.
An opts.isKeyword(id)
value that is a string will be mapped to existing types.
The only currently supported string value is "block"
.
nodes
Aside from the regular esprima data, you can also call
some inserted methods on nodes.
Aside from updating the current node, you can also reach into sub-nodes to call
update functions on children from parent nodes.
node.source()
Return the source for the given node, including any modifications made to
children nodes.
node.update(s)
Transform the source for the present node to the string s
.
Note that in 'ForStatement'
node types, there is an existing subnode called
update
. For those nodes all the properties are copied over onto the
node.update()
function.
node.parent
Reference to the parent element or null
at the root element.
install
With npm do:
npm install falafel
license
MIT