Creating custom Babel plugins

A talk on creating babel plugins and understanding AST. (Abstract Syntax Trees)

Babel is a compiler for next generation. It helps in making code transformations and building code mods easy. Here is the notes for my talk at Geeknight Meetup in Thoughtworks Chennai.

Github Slides

Why we need Babel ?

ECMA releases new specs and standards for javascript. These new specs are implemented by browser vendors. So, browsers will be able to execute lates code which is written using ES6. Often this takes a considerable time. Even if the implementation is successful, the clients should stay updated with browsers.

So, Babel helps in achieving this by transpiling ES6 syntax into ES5. Hence the browsers can execute them.

The win for DX over UX 💪 😅

Often this leads to the victory of Developer Experience over User Experience. A perfect scenario is having a Good Balance between Developer and User Experiences. The users with latest browsers, still end up loading bigger and older bundles.

How to balance both DX and the UX

We can generate two builds in our build phase.

  • esm
  • cjs

The esm build targets the latest browsers and the cjs targets old browsers. One way to do this is having two separate script tags.

<script type="module" src="/build/app.esm.js" />

If a browser support type="module". It can execute the esm bundle and hence it will load a smaller bundle and the second tag is ignore.

<script nomodule src="/buid/app.js" />

Stencil, is one of the popular frameworks does this out of the box.

Proptip - You can use cdn to load ESM modules for the repositoreis which expose them in their package.json files.

AST Trees

AST stands for Abstract Syntax Tree. It is a tree representation of the syntactic structure of source code written in a programming language.

These are widely used in compilers to represent the structure of the source code. We can use tools to understand it better.

The Process !

  • First the Babel compiler parses the code and generates a AST. This is done by using babel-parser. Babylon is the parser for babel which performs this step.

  • babel-traverse helps in traversing the AST. The traverser follows a visitor pattern in which it visit each node.

  • Now, in the traverse phase. We can perform any action that we can do on AST. Adding / Removing / Changing the AST.

Links