What is Babel?
Note: This is a response to this blog post by Julia Evans.
Browser support for template literals, courtesy of MDN.
sed on steroids.
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.