Best Practices" class="reference-link">Best Practices
Traversing the AST is expensive, and it’s easy to accidentally traverse the AST more than necessary. This could be thousands if not tens of thousands of extra operations.
Babel optimizes this as much as possible, merging visitors together if it can in order to do everything in a single traversal.
When writing visitors, it may be tempting to call path.traverse
in multiple
places where they are logically necessary.
path.traverse({
Identifier(path) {
// ...
}
});
path.traverse({
BinaryExpression(path) {
// ...
}
});
However, it is far better to write these as a single visitor that only gets run once. Otherwise you are traversing the same tree multiple times for no reason.
path.traverse({
Identifier(path) {
// ...
},
BinaryExpression(path) {
// ...
}
});
Do not traverse when manual lookup will do" class="reference-link">Do not traverse when manual lookup will do
It may also be tempting to call path.traverse
when looking for a particular
node type.
const nestedVisitor = {
Identifier(path) {
// ...
}
};
const MyVisitor = {
FunctionDeclaration(path) {
path.get('params').traverse(nestedVisitor);
}
};
However, if you are looking for something specific and shallow, there is a good chance you can manually lookup the nodes you need without performing a costly traversal.
const MyVisitor = {
FunctionDeclaration(path) {
path.node.params.forEach(function() {
// ...
});
}
};
When you are nesting visitors, it might make sense to write them nested in your code.
const MyVisitor = {
FunctionDeclaration(path) {
path.traverse({
Identifier(path) {
// ...
});
}
};
If you need some state within the nested visitor, like so:
const MyVisitor = {
FunctionDeclaration(path) {
var exampleState = path.node.params[0].name;
path.traverse({
Identifier(path) {
// ...
}
}
});
}
};
You can pass it in as state to the traverse()
method and have access to it on
this
in the visitor.
const nestedVisitor = {
Identifier(path) {
if (path.node.name === this.exampleState) {
// ...
}
}
};
const MyVisitor = {
FunctionDeclaration(path) {
var exampleState = path.node.params[0].name;
path.traverse(nestedVisitor, { exampleState });
}
};
Sometimes when thinking about a given transform, you might forget that the given structure can be nested.
For example, imagine we want to lookup the constructor
ClassMethod
from the
Foo
ClassDeclaration
.
class Foo {
constructor() {
// ...
}
}
const constructorVisitor = {
ClassMethod(path) {
if (path.node.name === 'constructor') {
// ...
}
}
}
const MyVisitor = {
ClassDeclaration(path) {
if (path.node.id.name === 'Foo') {
path.traverse(constructorVisitor);
}
}
}
We are ignoring the fact that classes can be nested and using the traversal
above we will hit a nested constructor
as well:
class Foo {
constructor() {
class Bar {
// ...
}
}
}
There are a few primary ways to test babel plugins: snapshot tests, AST tests, and exec tests. We’ll use for this example because it supports snapshot testing out of the box. The example we’re creating here is hosted in this repo.
First we need a babel plugin, we’ll put this in src/index.js.
// src/__tests__/index-test.js
const babel = require('babel-core');
const plugin = require('../');
var example = `
var foo = 1;
if (foo) console.log(foo);
`;
it('works', () => {
const {code} = babel.transform(example, {plugins: [plugin]});
expect(code).toMatchSnapshot();
});
This gives us a snapshot file in src/__tests__/__snapshots__/index-test.js.snap
.
exports[`test works 1`] = `
"
var bar = 1;
if (bar) console.log(bar);"
`;
If we change ‘bar’ to ‘baz’ in our plugin and run jest again, we get this:
Received value does not match stored snapshot 1.
- Snapshot
+ Received
@@ -1,3 +1,3 @@
"
-var bar = 1;
-if (bar) console.log(bar);"
+var baz = 1;
+if (baz) console.log(baz);"
We see how our change to the plugin code affected the output of our plugin, and
if the output looks good to us, we can run jest -u
to update the snapshot.
AST Tests
In addition to snapshot testing, we can manually inspect the AST. This is a simple but
brittle example. For more involved situations you may wish to leverage
babel-traverse. It allows you to specify an object with a visitor
key, exactly like
you use for the plugin itself.
it('contains baz', () => {
const {ast} = babel.transform(example, {plugins: [plugin]});
const program = ast.program;
const declaration = program.body[0].declarations[0];
assert.equal(declaration.id.name, 'baz');
// or babelTraverse(program, {visitor: ...})
});
Here we’ll be transforming the code, and then evaluating that it behaves correctly.
Note that we’re not using assert
in the test. This ensures that if our plugin does
weird stuff like removing the assert line by accident, the test will still fail.
it('foo is an alias to baz', () => {
var input = `
var foo = 1;
// test that foo was renamed to baz
var res = baz;
`;
var {code} = babel.transform(input, {plugins: [plugin]});
var f = new Function(`
${code};
return res;
`);
var res = f();
Babel core uses a similar approach to snapshot and exec tests.
babel-plugin-tester
This package makes testing plugins easier. If you’re familiar with ESLint’s this should be familiar. You can look at the docs to get a full sense of what’s possible, but here’s a simple example: