Using Babel to write cross-browser modern ECMAScript

This is going to be a short write-up to demonstrate how Babel can make your modern JS more portable.

Here’s a familiar situation you might relate to: You’re a Javascript developer who wants to use ECMAscript 2015 features in your code, but you can’t because you either a) have to support Internet Explorer or b) have to support mobile browsers. And believe it or not, with all the mobile-first craze, that’s a very common concern!

So you’re probably scratching your head thinking: “Well, how will I ever write ECMAscript 2015 like this?” Enter Babel.

Babel is an open-source JSX to JS compiler. So what it does is that it takes your element-wise JSX markup and converts it to JS that’ll work on a particular browser. And what happens is you can insert your ECMAScript 2015 code inside the JSX and that will also get converted using polyfills for older browsers, and this allows you to utilize newer features that would otherwise result in a syntax error on some browsers.

Installation and Running

Babel actually consists of a collection of packages. The library itself is located under babel-core, while the commands are contained in babel-cli and extensions to babel start with babel-plugin- . You usually want to install only babel-cli and this will automatically pull babel-core, and only install one of the babel-plugin- packages if you need that particular functionality.

Since it is a NodeJS package, you’ll usually want to install it locally, not globally. This can be done with npm install babel-cli. You also need to install the babel-preset-es2015 package as well because, without it, Babel will just spit out the input files onto the console. Then you can call Babel like this: babel src --preset es2015 --out-dir dir, where src is simply your root directory of source code, and “dir” is the folder where our files will be mirrored in but with the transpiled code, so that it’s not sent to the console.

There are many other flags that can be passed to Babel such as -s, for source maps. Source maps are special files that assist in debugging Babel-compiled Javascript. Another useful flag is -w which means “watch the current folder for any changes in the files and automatically compile them”. It’s an integral part of making webapps automatically load after a code update. All of these settings, including presets, can be placed in a .babelrc file so that you don’t have to spell them out on each run. See this page for details.

Also, by using libraries such as ui-logger-dom and services like BrowserStack, you can emulate any browser online to test your app on, and the console errors will be printed in the main (DOM) window instead of in the respective browser’s console, which may be difficult to access.

Developer at ChainWorks Industries