How to Use ES2015 Today with Babel and Gulp

ECMAScript 2015 (ES2015), formerly known as ES6, brings some great new features to JavaScript. These include block scoping, arrow functions, template strings, destructuring, and more.

In July 2015, Ecma International approved it as a standard. As with any new JavaScript functionality, it is not yet fully supported — even in modern browsers. (Check out current ES2015 browser support here.) Due to the inconsistent browser support, you will likely not be able to directly adopt ES2015 in your JavaScript code. However, there is a way to start using ES2015 today.

Transpilation to the rescue

A transpiler differs from a compiler in the output it generates. While a compiler transforms source code to machine code, bytecode, or other binary formats, a transpiler transforms source code into equivalent source code in another language or environment.

Enter Babel

Babel is an excellent tool that transpiles ES2015 code to equivalent ES5 code. This allows developers to write code using ES2015 syntax and have it run on browsers that don’t yet have ES2015 support. Babel even has a polyfill for adding runtime support for ES2015 features such as Maps, Promises, and Sets.

Formerly called 6to5, Babel has become the most popular JavaScript transpiler available today. It’s an open source project, and is supported on just about any JavaScript build system (Grunt, Gulp, Broccoli, etc.). It has a plug-in architecture, so that you can pull in only the features you need. This allows a project to incrementally add ES2015 functionality as needed.

Development environment

For this example, we’ll be using the following development environment:

Node.js

This is the runtime environment for our build tools. This also supplies the command-line npm (Node Package Manager) tool, which we’ll use to install Gulp, Babel, and related packages. To install Node, visit https://nodejs.org/.

package.json

The project information and dependencies are specified in a file called package.json, which is in the root directory of the project. If you don’t already have a package.json file, you can generate a new one by running:

npm init

NPM will ask you some questions about your project. For the purposes of this example project, you can just press Enter at each question to accept the defaults.

Gulp

Gulp is a stream-based build system. It’s very easy to get started.

  1. First, you’ll need to install the Gulp command-line tool globally:

npm install -g gulp

  1. This installs the gulp command. Next, install Gulp for the project:

npm install --save-dev gulp

This installs Gulp locally, and adds it as a development dependency in your package.json file.

  1. Once Gulp has been installed, create a new file called Gulpfile.js. In this file, we will require the Gulp runtime and create a skeleton build task that we’ll fill in later:

var gulp = require('gulp')
gulp.task('build', function() {
// We’ll fill this in after we install Babel
});

Babel installation and basic usage

The next step is to install Babel itself, and the es2015 preset:

npm install -g babel-cli
npm install --save-dev babel-preset-es2015

This installs the babel command-line utility.

Let’s run a small example file using it to demonstrate how Babel works. Here’s the input file, hello-world.js:

let name = 'World';
let greeting = `Hello ${name}!`

This simple example uses two ES2015 features. The first is the let keyword. let is used to declare variables in a block scope. On the second line, there is an example of template strings, which are special strings that support expression interpolation.

To transpile this example code into ES5, use this babel command:

babel --presets=es2015 hello-world.js > hello-world-es5.js

This command will read hello-world.js, transpile it, and save the results to hello-world-es5.js. Here’s the transpiled result:

'use strict ';

var name = 'World';
var greeting = 'Hello ' + name + '!';

As you can see, the template string expression was transpiled into an ES5-compatible simple string concatenation. Because there was no block scope, the lets were unnecessary, so Babel changed them into vars.

Note that Babel also added the string ‘use strict ‘; to the top of the file. This enables strict mode. Babel treats all source code as if it were an ES2015 module. One feature of ES2015 modules is that they are implicitly in strict mode. Because ES5 code is, by default, not in strict mode, the ‘use strict ‘; is needed to support this convention.

Adding Babel to your project

Using the CLI for transpilation is good for experimentation, but it’s better to use Babel from your project’s build system. In this section, we’ll set up Babel in our Gulp project. The process will be very similar for other build tools like Grunt or Broccoli. For information about using Babel with these tools, visit http://babeljs.io.

Adding Babel to a Gulp project is a very straightforward process.

  1. First, you’ll need to install the core gulp-babel package:

npm install --save-dev gulp-babel

  1. Now, let’s set up Babel in js. The first step is to require the gulp-babel package at the top of the file.

var babel = require('gulp-babel');

  1. Now we’ll fill in the build task we added to js earlier. This allows Gulp to run the source code through Babel. Due to the streaming nature of Gulp, you just pipe your source stream through a call to the babel function, which performs the transpilation.

gulp.task('build', function() {
return gulp.src('src/**/*.js')
.pipe(babel())
.pipe(gulp.dest('build'));
});

Configuring Babel

First, create a Babel configuration file, .babelrc, in the project root directory. Babel configuration is stored in JSON format.

Using individual plugins

If you want to keep the scope of your ES2015 code narrow, you may want to only enable certain transformations. Each of these plugins is installed as an NPM package, and then it is registered in the .babelrc file. For this example, let’s use template strings and block scoping.

  1. First, we’ll install the packages:

npm install --save-dev babel-plugin-transform-es2015-template-literals
npm install --save-dev babel-plugin-transform-es2015-block-scoping

  1. Then, register these plugins with Babel in .babelrc:

{
'plugins': [
'transform-es2015-template-literals',
'transform-es2015-block-scoping'
]
}

Now you can use template strings and block scoping in your source code and Babel will transpile it to ES5 code.

Using a preset

A Babel preset is a collection of plugins. This allows a less verbose configuration file if you want to use all of ES2015. For this example, we’ll use the es2015 preset that we installed earlier. Register this preset in the presets section of your .babelrc file:

{
'presets': ['es2015']
}

That’s it! ES2015 syntax is now usable in your project.

ES2015 runtime: Using the Babel polyfill

Transpilation of ES2015 to ES5 is only one piece of Babel. Some new ES2015 features go beyond just syntax. These features, like Map or Set, require runtime support. This support is provided via a polyfill, which is an ES5 implementation of the new ES2015 features.

The way to use the polyfill depends on the type of application you are developing.

CommonJS modules

CommonJS modules are used by Node applications, as well as browser-based projects using a tool like Browserify or Webpack. For a CommonJS environment, install the polyfill using NPM:

npm install --save-dev babel-polyfill

Once the polyfill is installed, simply require it like any other CommonJS module:

require('babel-polyfill');

Browser-based projects

For other browser-based projects, you will need the polyfill.js file from a Babel polyfill installation. The easiest way to get this is to run npm install babel-polyfill, then copy the polyfill.js file from the dist directory in the installed module.

Once you have polyfill.js, include it in your application via a script tag. In order for the polyfill to work, it must be included before any compiled ES2015 code from Babel.

Wrapping up

At this point, we have done the following:

  • Installed and set up Babel to transpile ES2015 code to ES5
  • Experimented with Babel’s command-line tool
  • Created a Gulpfile that transpiles code in the src directory into the build directory
  • Installed the Babel polyfill to provide ES2015 runtime support

That’s all you need to use modern JavaScript today!

Babel has other transformations available, including some ES2016 features (available in differing stages). It can also be used to transpile React JSX files.

Another helpful Babel command – babel-node – can be used to run Node applications written in ES2015. It performs transpilation from ES2015 to ES5 on the fly. However, babel-node is not recommended for production use due to the overhead of transpiling on the fly.

For more information and documentation about Babel, visit the website at http://babeljs.io/.

Are there other tools, or specific Babel commands you find to be helpful? Comment in the discussion section below!

Leave a Comment