- Best Practices" level="1">Best Practices
- Create Helper Builders and Checkers" level="2"> Create Helper Builders and Checkers
- Avoid traversing the AST as much as possible" level="2">Avoid traversing the AST as much as possible
- Optimizing nested visitors" level="2">Optimizing nested visitors
- Being aware of nested structures" level="2">Being aware of nested structures
- Unit Testing" level="2">Unit Testing
Best Practices" class="reference-link">Best Practices
Create Helper Builders and Checkers" class="reference-link"> Create Helper Builders and Checkers
It’s pretty simple to extract certain checks (if a node is a certain type) into their own helper functions as well as extracting out helpers for specific node types.
function isAssignment(node) {
return node && node.operator === opts.operator + "=";
}
function buildAssignment(left, right) {
return t.assignmentExpression("=", left, right);
}
Avoid traversing the AST as much as possible" class="reference-link">Avoid traversing the AST as much as possible
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.
Merge visitors whenever possible" class="reference-link">Merge visitors whenever possible
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() {
// ...
});
}
};
Optimizing nested visitors" class="reference-link">Optimizing nested visitors
When you are nesting visitors, it might make sense to write them nested in your code.
const MyVisitor = {
FunctionDeclaration(path) {
path.traverse({
Identifier(path) {
// ...
}
});
}
};
However, this creates a new visitor object every time FunctionDeclaration()
is
called. That can be costly, because Babel does some processing each time a new
visitor object is passed in (such as exploding keys containing multiple types,
performing validation, and adjusting the object structure). Because Babel stores
flags on visitor objects indicating that it’s already performed that processing,
it’s better to store the visitor in a variable and pass the same object each
time.
const nestedVisitor = {
Identifier(path) {
// ...
}
};
const MyVisitor = {
FunctionDeclaration(path) {
path.traverse(nestedVisitor);
}
};
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) {
if (path.node.name === exampleState) {
// ...
}
}
});
}
};
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 });
}
};
Being aware of nested structures" class="reference-link">Being aware of nested structures
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 {
constructor() {
// ...
}
}
}
}
Unit Testing" class="reference-link">Unit Testing
There are a few primary ways to test babel plugins: snapshot tests, AST tests, and exec tests. We’ll use jest 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.
module.exports = function testPlugin(babel) {
return {
visitor: {
Identifier(path) {
if (path.node.name === 'foo') {
path.node.name = 'bar';
}
}
}
};
};
Snapshot Tests
Next, install our dependencies with npm install --save-dev babel-core jest
, and
then we can begin writing our first test: the snapshot. Snapshot tests allow us
to visually inspect the output of our babel plugin. We give it an input, tell it to make
a snapshot, and it saves it to a file. We check in the snapshots into git. This allows
us to see when we’ve affected the output of any of our test cases. It also gives use a diff
in pull requests. Of course you could do this with any test framework, but with jest updating
the snapshots is as easy as jest -u
.
// 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: ...})
});
Exec Tests
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();
assert(res === 1, 'res is 1');
});
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 RuleTester 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:
import pluginTester from 'babel-plugin-tester';
import identifierReversePlugin from '../identifier-reverse-plugin';
pluginTester({
plugin: identifierReversePlugin,
fixtures: path.join(__dirname, '__fixtures__'),
tests: {
'does not change code with no identifiers': '"hello";',
'changes this code': {
code: 'var hello = "hi";',
output: 'var olleh = "hi";',
},
'using fixtures files': {
fixture: 'changed.js',
outputFixture: 'changed-output.js',
},
'using jest snapshots': {
code: `
function sayHi(person) {
return 'Hello ' + person + '!'
}
`,
snapshot: true,
},
},
});