Using ES6 with Babel

Some of the modern browsers are yet to catch up with the new language additions to ES6. This means we have to use Babel to transpile our code into ES5.

Let’s look at the steps we need to follow to get this going.

Install Babel

Installing Babel CLI is the first thing we’ll do.

npm install babel-cli ––save–dev

We have to install addons to use new syntax additions, so let’s install babel-preset-es2015.

npm install babel-preset-es2015 ––save–dev

Create .babelrc

In order to create a preset to use Babel, we have to create a .babelrc file.

{
  "presets" : ["es2015"]
}

Same time let’s create a package.json file. Run the following command and follow the prompts.

npm init

Now we are ready to write some ES6 code!

Write ES6 Code

To test out the configuration is correct, let’s write our code in ES6 syntax.

Create a folder called src and then a file inside it called index.js and add the following code.

export const bar = foo => `${foo} world!`;

Transpile to ES5

To transpile our ES6 code, we will add a command to the script section of the package.json file.

"scripts": {
  "start": "./node_modules/.bin/babel src -d dist",
  ...
},

Now run the following command to let the transpilation kick in.

npm start

You will find a dist folder in your root directory with the transpiled code, which may look as follows.

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var bar = exports.bar = function bar(foo) {
  return foo + " world!";
};

Test

To guarantee our transpiled code is working, let’s write some tests.

First, let’s install Mocha and Chai.

npm install mocha chai ––save–dev

Also create a directory called test and add the test script to package.json.

"scripts": {
  "start": "./node_modules/.bin/babel src -d dist",
  "test": "mocha"
},

Now let’s write a test. Create a test.js file in the test directory and add the following test.

var assert = require('chai').assert;
var bar = require('../dist/').bar;

describe('Bar', function() {
  it('Should return Hello world!', function() {
    assert.equal(
      bar('Hello'),
      'Hello world!'
    );
  });
});

The test should pass and our ES6 transpilation is working!

Conclusion

ES6 and beyond is the future. Babel enables us to write futuristic code now.

The source code for this article can be found here on GitHub.

Be first to comment

Leave a Reply