Skip to content

Babel

!babel logo

What is it?

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

  • Transform syntax
  • Polyfill features that are missing in your target environment (through @babel/polyfill)
  • Source code transformations

Babel has support for the latest version of JavaScript through syntax transformers.

These plugins allow you to use new syntax, right now without waiting for browser support.

Example

// Babel Input: ES2015 arrow function
[1, 2, 3].map((n) => n + 1);

// Babel Output: ES5 equivalent
[1, 2, 3].map(function(n) {
  return n + 1;
});

Transpiling

Transpilers, or source-to-source compilers, are tools that read source code written in one programming language, and produce the equivalent code in another language which is in the same level.

What is transpiling then?

It is a process of taking one language & convert it in to another like you transpile your typescript into javascript and sass into css.

What is the difference between compiling & transpiling?

Compiling convert one language to another at lower abstraction level like java to byte code while transpiling convert one language to another at same abstraction level like typescript to javascript or sass to css.

Polyfilling

A polyfill is code that implements a feature on web browsers that do not support the feature.

When we use modern features of the language, some engines may fail to support such code. Here Babel comes to the rescue.

In order for certain features to work they require certain polyfills. You can satisfy all Babel feature requirements by using @babel/polyfill.

There are two parts in Babel:

  • Transpile the code
  • Polyfill.

The transpiler rewrites the code, so syntax features are covered. But for new functions, we need to write a special script that implements them. JavaScript is a highly dynamic language, scripts may not just add new functions, but also modify built-in ones so that they behave according to the modern standard. There’s a term “polyfill” for scripts that “fill in” the gap and add missing implementations.