Getting started with Babel

Like using cutting-edge JavaScript syntax and features? Then you should probably consider running Babel on your code before it goes live.

Babel is a third-party transpiler for JavaScript that can convert your shiny, modern JavaScript code into ES5 (2009) format. This improves its backwards and cross-browser compatibility.

In this tutorial, we cover why Babel is useful and how to install and start using it in your JavaScript projects.

Table of contents

What is Babel, and why use it?

Babel is a third-party transpiler for JavaScript. In plain English, it will take your JavaScript code and convert any modern features (ES2015+) into older, ES2015 syntax.

The reason you would want to do this has to do with browser-compatibility.

JavaScript browser compatibility issues

As you are probably already aware, JavaScript is the language of the web. It is a programming language that is understood by all modern browsers.

But when new JavaScript features are released, there are two potential bottlenecks on them working successfully in a user’s browser:

  1. A browser manufacturer is slow to implement the features.
  2. A user is slow to update their browser.

These two issues make browser-compatibility a really difficult issue: there are a multitude of browsers that updates unevenly, and individuals update their browsers unevenly too.

So to make your JavaScript really browser-friendly, you need to write code that is both compatible for somebody using the latest version of Chrome and someone using an outdated version of Internet Explorer and someone using some version of Opera, etc.

The way that you can achieve this is simple: use old JavaScript syntax that is understood by a user’s browser, even if it is slow to implement new features and/or a user hasn’t updated their browser in a while.

Annoyingly, this means that, if you want to achieve backwards and cross-browser compatibility, you should only use old JavaScript syntax in production.

This is where Babel comes in: by transpiling your modern code into ES2015 syntax, you are free to use the latest JavaScript tips and tricks, while leaving Babel to take care of converting it into syntax that is browser-friendly.

Using Babel online

One way to start using Babel is live on their website. Type in modern JavaScript code in the left-hand pane and old, browser-friendly ES2015 JavaScript will be output on the right!

For example, for the following input…

/* Your modern JavaScript code */

async function myFunction() {
    try {
        const res = await fetch('http://httpbin.org');
        data = await res.json();
        console.log(data);
    } catch(e) {
        console.log(e);
    }
};

…Babel produces the following output:

/* Babel output */

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function myFunction() {
  return _myFunction.apply(this, arguments);
}

function _myFunction() {
  _myFunction = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var res;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return fetch('http://httpbin.org');

          case 3:
            res = _context.sent;
            _context.next = 6;
            return res.json();

          case 6:
            data = _context.sent;
            console.log(data);
            _context.next = 13;
            break;

          case 10:
            _context.prev = 10;
            _context.t0 = _context["catch"](0);
            console.log(_context.t0);

          case 13:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 10]]);
  }));
  return _myFunction.apply(this, arguments);
}

;

It’s not pretty!

But the beauty of Babel is you don’t have to work with it directly. You only need to make sure your HTML document reads the Babel-compiled JavaScript and not the source code.

You can use Babel in this way: copy and pasting the ES2015 syntax and using it in your project. But this will probably become quite annoying quickly, especially if you are updating regularly and have a large code base.

Instead, you can install Babel in your project folder and automate the process from the command line.

Installing Babel

Make sure Node.js is installed

You can install Babel from the command line in your terminal using npm.

To do this, you need to have Node.js installed on your computer.

Not sure if you have installed Node.js? Type the following line of code in your terminal to check the currently installed version.

node -v

If this does not return a version number (e.g. v16.14.2), head to the Node.js website to download and install it on your system.

Next, navigate to a new empty folder in the terminal and call the following to create a new Node project:

npm init --yes

The --yes parameter will accept default settings for the new project (fine for testing). If successful, you should now see a package.json file in the root folder of your project directory as well as a node_modules folder inside which we can install Babel using the Node Package Manager (npm).

Install Babel using npm

To install Babel, use the following command in the terminal:

npm install --save-dev @babel/core @babel/cli @babel/preset-env
  • --save-dev: Install as a development dependency.
  • @babel/core: The core Babel package.
  • @babel/cli: Allows Babel to run from the command-line.
  • @babel/preset-env: Installs transpiling presets.

Next, to make life easier, open package.json and add a "build" property with the value "babel src -d lib" inside "scripts":

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel src -d lib"
  }

Now, when you use the command npm build, it will run the command babel src -d lib for you.

This sets the directory that Babel gets JavaScript code from to src and the output folder to lib.

Now, create a new folder called src in the root directory of your project and place and JavaScript code you want Babel to transpile inside it.

There is no need to create a new folder named lib as Babel will do this when it runs.

Configuring Babel

Run npm build from the command line in your terminal now and Babel will run.

But open the lib folder and look at the output. It probably won’t be the result you were hoping for:

/* project/src/script.js */

async function myFunction() {
    try {
        const res = await fetch('http://httpbin.org');
        data = await res.json();
        console.log(data);
    } catch(e) {
        console.log(e);
    }
};
/* project/lib/script.js */

async function myFunction() {
  try {
    const res = await fetch('http://httpbin.org');
    data = await res.json();
    console.log(data);
  } catch (e) {
    console.log(e);
  }
}

;

The formatting is a little different, but it’s exactly the same code!

The reason is that Babel still needs to be configured to transpile your code in a certain way. That’s where our @babel/preset-env install is useful.

Because this command installed presets, all you need to do is specify that you want to use them.

To this, create a babel.config.json file in the root directory of your project. Babel checks for this when it runs, so you don’t need to configure any other files.

Now, to use your installed presets, set the content of the file to a JSON object with a presets property and a “@babel/preset-env” inside an array:

{
    "presets": ["@babel/preset-env"]
}

Now save babel.config.json.

Results

Now, run npm build again from the command line. Now, check the contents of the lib folder.

Your script should now be transpiled and ready to use!

For example, the following script…

/* project/src/script.js */

const add = (x, y) => x + y;

…is output as this:

/* project/lib/script.js */

"use strict";

var add = function add(x, y) {
  return x + y;
};

Note that if you have more than one JavaScript file, they will all be converted to a new file.

So a second script in the src directory containing this…

/* project/src/secondaryScript.js */

const array = ["apples", "pears", "bananas"];

const arrayTwice = [...array, ...array];

…outputs this:

/* project/lib/secondaryScript.js */

"use strict";

var array = ["apples", "pears", "bananas"];
var arrayTwice = [].concat(array, array);
console.log(arrayTwice);

Summary

Browser compatibility is a must if you want your website or app to work for all users.

But writing ES2015 code for the rest of time to achieve this would be tiresome and inefficient.

The beauty of Babel is that it helps you to achieve this outcome without personally having to rewrite your code.

Instead, you can continue writing JavaScript with shiny new syntax and features.

Related links