Using Gulp to transpile ES6 to ES5 with Babel

Working through the Node School courses as well as the projects for Free Code Camp I have really been trying to write all my JavaScript in ES6 then I would run babel each time to transpile the file to ES5. Just the other day I was reading through the node website and most ES6 syntax is supported already, just make sure you have 'use strict';. However considering most browsers do not support ES6 yet, and JavaScript will continue to evolve in the future, I feel it is good practice to learn how to set up a gulp task to automate this process for me.

Finally learning gulp was a dream for me since I was able to automate every mundane task I was doing manually for creating a website. These task were; transpiling ES6 to ES5 with babel. Minifying the JavaScript and CSS files. Oh and not to mention using Sass and Compass to convert the style sheets to normal CSS. Then open on a browser, or reload if already up. Over time this gets very boring and trying to find the right style declaration to position an element takes repeated changes and refreshes! It was during the time I was redesigning my portfolio page that I wrote my first gulp file!

This post is going to focus on setting up a gulp task that will transpile your ES6 code to ES5. For this let I like to enclose all the files made by babel into a folder called dist. That way they are somewhat out of sight, allowing me to focus on writing and learning ES6 syntax. You will need to have node and npm installed, but I will be hoping that is a mute point. The first thing I do is run.

terminal

npm init

The setup will walk you through this file. Most tutorials just have you enter through the steps as they are fairly self explanatory, like name of project, version, description and author. There is a package.json file create which will have a listing of all your install npm modules as long as you run npm install with the --save or --save-dev flag. More on npm modules can be found on the docs which I found very helpful. Next let us install the modules we need to setup our gulp.task().

terminal

npm install --save-dev gulp gulp-babel babel-core

Which should give you a file similar to this one I have from my browserify-adventure module.

package.json file created by npm init

{
  "name": "browserify-adventure",
  "version": "1.0.0",
  "description": "",
  "main": "beep_boop.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "babel-core": "^5.8.25",
    "gulp": "^3.9.0",
    "gulp-babel": "^5.2.1"
  }
}

As you can see the modules we installed were added to the "devDependencies" if we used the --save flag instead then they will show up in "dependencies" like the uniq module which is needed for browserify-adventures.
packageJSON
I found a helpful stackoverflow.com answer to help explain the difference between the two.

At this point we are ready to write the gulpfile. Now you maybe asking if we are going to use gulp to run babel to convert our JavaScript files, does that mean we have to first write the gulpfile.js as old ES5. I answer you absolutely not. Because wee downloaded babel-core we can change the name of the gulpfile.js to gulpfile.babel.js and happily write everything in ES6!

Terminal

// make gulpfile
touch gulpfile.babel.js

// open the file in text editor, I use sublime text
subl gulpfile.babel.js

Gulpfile contents

import gulp  from 'gulp';
import babel from 'gulp-babel';

gulp.task('es6', () => {
    gulp.src('./*.js')
        .pipe(babel({
            ignore: 'gulpfile.babel.js'
        }))
        .pipe(gulp.dest('./dist'));
});

gulp.task('watch', () => {
    gulp.watch('./*.js', ['es6']);
});

gulp.task('default', ['es6', 'watch']);

So first we import gulp and gulp-babel. Next we write the task itself. The first param is the name of the task as a string. This could be anything you would like. 'es6' I feel is good for this example. Using the arrow function syntax we pass an anonymous function as the second argument to the gulp.task() method. Inside that we use gulp.src() to find the relative path to the JavaScript files we want to transpile. In this example the files are in the same folder as the gulpfile.js. Next we .pipe() the files to babel() which takes an optional options object. Since the gulpfile.babel.js matches the glob pattern we need to ignore passing it through babel(). This could have been avoided if we placed out JavaScript files in a different directory then the gulpfile.babel.js. Anyway! Finally we .pipe() the transpiled files to gulp.dest() which takes an string path as the argument and location to create the output file. Here I place all the ES5 output code in a folder named /dist a convention I keep seeing with code on github.com.

The second task is 'watch' which will do exactly that; watch file(s) for changes and then run one or more tasks when that happens. In this simple example we are only watching the JavaScript file in the current directory ('./*.js'). This is the first argument to the gulp.watch() method. The second argument is an array of (string) tasks to run. So anytime one of the ./*.js files changes then gulp will run the 'es6' task again.

Our third task bring everything together! gulp.task('default', ['es6', 'watch']) In your terminal at the root of your project where your gulpfile.babel.js resides running gulp as a command will look for the gulpfile and the 'default' task. Our default task takes an array of tasks to run as the second argument.

gulpWatch

To stop gulp just press Ctrl+c. And to start again just run gulp in your terminal at the root of your project. Now all the ES6 files you write will be transpiled to ES5 and be created in the /dist directory. Obviously these paths can be changed to whatever suits your needs best.

Advertisements

One thought on “Using Gulp to transpile ES6 to ES5 with Babel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s