~ 2 min read

Primer to Babel.js

share this story on
I’m sure you’re interested in ES6, supporting JSX, etc.So I worked out this intro so you can get up to speed really quick and really clear…

I’m sure you’re interested in ES6, supporting JSX, etc.
So I worked out this intro so you can get up to speed really quick and really clear (I hope!)

This is the bare-bones, quickest intro to everything you need to know about Babel.

Interlude

Babel compiles JavaScript code, to JavaScript code. Not so complicated, right?
It needs to do it because there are different versions of the JavaScript engines and developers want to use bleeding edge code syntax and functionality but also supporting old JavaScript engines running on older browsers or Node.js versions.

Babel’s high-level architecture broken in two main packages:

  • babel-cli — helps with running babel from the command line for compiling file by file.
  • babel-core — the core babel library for Node.js.

There are many other npm modules which are integrations like gulp-babel, or babel-loader for webpack, as well as the babel collections of transformations like babel-preset-es2015 and so on. We’ll touch the latter in a sec.

How Babel Works, in a nutshell

Babel is just a compiler.
It has 3 stages where things happen:

  1. Parsing — a piece that knows how to parse JavaScript code. By default this is what Babel does in it’s core.
  2. Transforming — a piece that knows how to apply any sort of transformations based on the parsed data. For example:
    const h = ‘hello’ and converting it to var h = ‘hello’.
  3. Generating — Applies the generated transformations.

Babel’s modularity

Plugins, Presets, and Pollyfils:

  • Plugins — plugins are specific set of transformations that are applied to syntax. For example, supporting arrow functions in ES6. As you can imagine, there are many plugins that are created to cover all of ES6.
  • Presets — presets are simply a collection of plugins. They are just a bundle of the plugins, no extra sugar.
  • Pollyfils — these are plugins that pollyfil a specific set of functionality that is not yet available in the runtime engine, hence require an actual implementation. For example: Object.assign in ES6.

Resources

Learn more about Babel:

Plugins · Babel
_The compiler for writing next generation JavaScript_babeljs.io

Want to know more about compilers like Babel? check out the following project:

thejameskyle/the-super-tiny-compiler
_the-super-tiny-compiler - :snowman: Possibly the smallest compiler ever_github.com