Skip to Main Content

Getting Ahead of the Curve: ECMAScript 6 Development Today with Babel and Grunt

ES2015

Andrew Bogdanov, Accusoft Software Engineer

The brand new ECMAScript standard, ES2015, is finally out. The standard is a hot new thing in the JavaScript community today. After a long period of living with imperfections of the ES5 standards, we’re finally making a shift to a newer and happier world of structural code. However, if you try to write your code according to the new specs, you will understand that browser incompatibility is still here and it’s not going anywhere in the near future. We are still stuck with “lovely” Internet Explorer that won’t support this new standard, ever! Other popular browsers are making their way through the woods but are still not there yet. However, there is a way out! The tool that can help us get the widest browser support is called Babel. It’s a transpiler that can turn new syntax of ES6 to an ES5 construct that all current browsers up to IE8 can understand.

 

It all starts with a build tool

Welcome our guest for today: Grunt. You might have heard of this build tool before, as it is quite versatile. Today we will use it for setting up a Babel transpiling process. So let’s get started.

 

Project Files

After the end of every step of this article, I will provide you with a project files relevant to that step. In case you would like to skip ahead and just look at the final code, you can download it here. Just don’t forget to do npm install before running the project.

 

Step 1: Create the project’s basic structure

Let’s start creating the project structure that we will use for our ES6 development. I will use WebStorm for writing the code here, but you can use any IDE you like.

Let’s go to our IDE of choice and create a new project called BabelSetupGrunt. Inside our new project, create a folder called es6—this folder will contain all of the ES6 JavaScript files that we will need to compile to ES5. To keep things simple, let’s add one js file called “main.js” into that folder. That file, once compiled, will be placed into a folder called “js,” that we also need to create. The name of the compiled file will remain the same. We will target that file in our HTML web page.

In order to get us going, I will add a simple ES6 styled variable declaration and a console log that utilize new string interpolation syntax (don’t worry if you don’t know what those are. We will go over those features in greater detail in future articles). So the code in the file should look like this:

let es6 = 'es6';
console.log(`Hello ${es6}`);

I will also add a simple index.html file, where we will target our compiled js file that we will add later.

The resulting structure for this step should look like this:
ECMAScript 6 Development

You can download it here: link

 

Step 2: Add dependencies

In this step, we will use npm to install all required dependencies.

Prerequisites:
All of our build tools will require Node.js. So, if you don’t already have one installed, go to nodejs.org and install the latest stable version.

After you’ve made sure you have latest version of Node and npm installed, open the windows command prompt and start entering the commands below.

  1. Install Grunt globally. You can execute this command from any folder.
    npm install grunt-cli -g
  2. After Grunt has been installed globally, make sure you are at the root level for the project’s directory. In my case, a command to get into it would be:
    cd C:ProjectsStudy[JavaScript]ES2015BabelSetupGrunt
  3. Next we want to create a new npm package file that will hold all of our project’s dependencies. Instead of filling out an answer for every question about our project, we will use a quicker way by adding -y flag at the end of the command. It will create package.json file with all default values that we can change later if we’d like.
    npm init -y
  4. Now we will install Grunt locally. We will save it as a dev-dependency in our package.json file so we could install it later on some other machine with simple npm i. I will use an “i” shortcut for every “install” command just to make typing a bit quicker.
    npm i grunt --save-dev
  5. Next we need to install a Grunt-Babel plugin, also saving it as a dev-dependency.
    npm i grunt-babel --save-dev
  6. In future projects, I would like to use the latest features provided by the ES2015 standard. The Grunt-Babel plugin doesn’t support it out of the box. In order to use it, we will need to additionally set up a presets collection called babel-preset-es2015.
    npm i babel-preset-es2015 --save-dev

Project files for this step: link

 

Step 3: Create a Grunt task

Now let’s create a gruntfile.js and add a “babel” task into it.

module.exports = function (grunt) {
   'use strict';
   grunt.initConfig({
       babel: {
           options: {
               sourceMap: true
           },
           dist: {
               files: {
                   'js/main.js' : 'es6/main.js'
               }
           }
       },
   });
   grunt.loadNpmTasks('grunt-babel');
   grunt.registerTask('default', ['babel']);
};

Here’s a little breakdown of what we’ve just written.

  1. Babel task can be configured by passing an “options” object. We specify a sourceMap property in order to have sourceMaps that can point to the original ES6 files. It will become very handy when we’ll start to debug the code.
    options: {
                   sourceMap: true
               }
    
  2. We specify the destination folder where we want our transpiled files to be saved.
    dist: {
                   files: {
                       'js/main.js' : 'es6/main.js'
                   }
    
  3. Next we need to load the npm task. Note that this should happen after initConfig method.
    grunt.loadNpmTasks('grunt-babel');
  4. And lastly we should register a task so we can run it. We will name our task “default.” Doing so, we will be able to run grunt from the console without specifying any additional parameters.
       grunt.registerTask('default', ['babel']);
  5. Remember those 2015 presets we installed earlier? We will need to provide them to our grunt task. There are two ways for doing so. First is to create .babelrc file in the root directory of our project and populate it with some settings.
    {
       "presets": ["es2015"]
    }

    The second way is to provide that information to our Grunt Babel task options as a “presets” property.

    grunt.initConfig({
       babel: {
           options: {
               sourceMap: true,
               presets: ['es2015']
           },

Feel free to try both of them and choose an option that works better for you. I find the first option a bit more clear and modular, so I will go with it.

Now we can try writing grunt in the console and see the new file that’s been created in our js directory. Let’s target that file in the index.html file like so

script type="text/javascript" src="js/main.js">

and open it in the browser. If you did everything correctly, you will see a message in the console: “Hello es6”
Project files for this step: link

 

Step 4: Adding a watch

The task is complete and can be used but usually I don’t like to hit that grunt command every time I do any modification to the file, so why don’t we enhance the grunt file with a watch task. That way Grunt will be re-transpiling files on every change that we make inside es6 folder. In order to do so, we will need to install one additional dependency. It’s called grunt-contrib-watch.

npm i grunt-contrib-watch --save-dev

The resulting file with watch task:

module.exports = function (grunt) {
   'use strict';
   grunt.initConfig({
       babel: {
           options: {
               sourceMap: true
           },
           dist: {
               files: {
                   'js/main.js' : 'es6/main.js'
               }
           }
       },
       watch:{
           scripts: {
               files : ['es6/*.js'],
               tasks: ['babel']
           }
       }
   });
   grunt.loadNpmTasks('grunt-contrib-watch');
   grunt.loadNpmTasks('grunt-babel');
   grunt.registerTask('default', ['babel']);
};

You can start the task by typing grunt watch in the console.

Congratulations! If you got to this point, you should be all set to start using ES6 today. You can also compare your results with the final project structure here. In upcoming articles, we will start looking into new features of ES6.


Andrew Bogdanov is a Software Engineer and Scrum Master at Accusoft. He is passionate about the web and loves to code useful and intuitive applications. He holds a Bachelor in Computer Science from Kyiv Slavonic University. In his free time, Andrew enjoys performing fingerstyle guitar arrangements for friends and family.