What is Babel?
Note: This is a response to this blog post by Julia Evans.
Babel is a common part of many frontend build pipelines. But what is it, and what would you use it for? To answer that question, let’s first take a step back and talk about web browsers and Javascript.
Modern Javascript has learned many tricks in the recent years (such as nullish coalescing, template literals, default parameters, and many more). These new language features often allow the developer to write code that’s either more robust, or shorter, or easier to reason about, or all of the above. Alas, many of your users may be using an older browser that was released before these features made it into the language spec. What’s a developer to do?
Browser support for template literals, courtesy of MDN.
Enter Babel. Many of the newer Javascript features could already be implemented in older versions of the language, but the code was often verbose and messy.
Babel can take Javascript code that’s written using newer language features and turn it into (usually slightly messier) code that’s backwards compatible with older browsers.1. 2. Babel is a tool that can map from one source code to a different, functionally equivalent source code. You can think of Babel as a syntax-aware sed
on steroids.
As an example, let’s look at nullish coalescing, a feature that’s common in many modern languages, but not in older Javascript. Using the newer syntax, you might write code like this:
const foo = null ?? "default value";
console.log(foo); // output: "default value"
const bar = "value" ?? "default value";
console.log(bar); // output: "value";
Putting the above code through Babel and targeting browsers which don’t support ??
might yield something like this:
const leftFooValue = null;
const foo = leftFooValue != null
? leftFooValue
: "default value";
console.log(foo); // output: "default value"
const leftBarValue = "value";
const bar = leftBarValue != null
? leftBarValue
: "default value";
console.log(bar); // output: "value";
The functionality is the same, but you don’t have to worry about older browsers not understanding the syntax.
This is one specific example of why Babel is used and what it can do, but Babel addresses the general case for transforming code. Much like with sed
, your imagination is the limit.
1. This is a coarse simplification. Babel can also be used for many other purposes besides backwards compatibility, such as supporting JSX templates (which no browser supports natively), or integrating Typescript with the rest of your build tools etc.
2. In practice, Babel is configured based on available features, not browsers. Browserslist is a tool which allows you to bridge the gap and specify which browsers you want to target for browser compatibility instead. For this reason, Browserslist is commonly used in conjunction with Babel, often behind the scenes of various frontend build toolchains.