Getting Started with Babel Plugins

Babel is the goto transpiler for JavaScript. One of the most powerful features is to allow you to easily create your own plugins. With this we can create awesome developer experiences.

It all begins with a concept of parsing what is known as the Abstract Syntax Tree (AST for short).

The AST is the result of parsing your syntax and mapping each element to a node within the tree. Each node can have different properties but all obey a common interface.

Let’s take a simple example such as 1 + 1.

It starts with a Program node which body contains an expression statement.

This expression statement then has an expression that is of a type BinaryExpression.

The BinaryExpression has three parts to it the operator (+) along with left and right assignments both in this case being literals (1 and 1).

When creating a Babel plugin we are provided with the API to traverse the AST. We can tell the plugin to then act on certain types of nodes. This concept is know as a visitor. The pattern itself is known (unsurprisingly) as the visitor pattern.

To explain the concept of the visitor pattern we can implement a simplistic version of it based on our 1 + 1 AST above:

In Babel the AST conforms to a specification known as ESTree. It is worth taking a look at the specification to get a brief understanding of each node object. It will come in very handy when you start creating your Babel plugin.

Now we understand some fundamentals of how ASTs can be traversed we can start creating our first plugin.

To create a plugin we can use a starter template to get things going.

As you can see in the specs the example shows the following code:

const example = “Hello”;

Let’s say that in our application we want all strings (who knows why?!) of “Hello” to become “World”. To do this we can write a plugin that when a Literal (“Hello”) is visited the value is replaced with “World”.

Let’s take a look at how the code would look to produce our required result.

Based on our previous understanding we can see that implementing a change to every StringLiteral is as simple as creating a visitor and replacing the nodes value if it equals “Hello” to “World”.

There you have it, easy and simple. From here you can expand on each visitor to make much more elaborate (and useful) Babel plugins.

Here are some useful resources whilst you are developing plugins for Babel:

More advanced topics around the Babel API and other features.
JavaScript AST explorer
Helpful tool to explore what an AST might look like for your plugin result.
Show your support

Clapping shows how much you appreciated Jon Sharratt’s story.