Basics of setting yourself up with Gulp and Babel.

In this example I am going to look at compiling ES6 to ES5 using Babel, but this example will work with compiling your React jsx code as well. As long a you know how to configure Babel.

Project Structure

This is what my project folder structure looks like:

|-- dist // Build will end up here
|-- src // All source code should be inside this folder
|-- index.js
|-- gulpfile.js

Our src/index.js contains the ES6 code and gulp will create a compiled version inside the /dist folder.

The ES2015 code I am using to test is

setTimeout(() => { console.log("ES2015 FTW"); }, 1000);

npm install

Let’s install everything we need

Babel

We need the babel core, CLI and es2015 preset:

$ npm install --save-dev babel-cli babel-core babel-preset-es2015

Gulp

We need gulp and the babel module for gulp.

$ npm install --save-dev gulp gulp-babel

Also make sure you have gulp installed globally.

Configuration

Babel

Configure babel to use the es2015 plugin in your package.json (or .babelrc if you prefer).

"babel": {
"presets": ["es2015"]
}

Gulp

Create your gulpfile.js and require the two gulp libs:

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

Then declare our default task:

gulp.task('default', function () {

});

Then for our task content:

  • Pick up the js files in /src
  • Compile it with babel
  • Put everything in /dist
gulp.task('default', function () {

return gulp.src('src/**/*.js')
.pipe(babel())
.pipe(gulp.dest('dist'));
});

Run the build script

Run the build script using

$ gulp

And your compiled files will be in the output folder.

This is what my index.js looks like after being transpiled:

"use strict";

setTimeout(function () {
console.log("ES6 FTW");
}, 1000);

Note

If you want to write your gulpfile.js in ES2015 and your version of node does not support it, follow the instructions in this article.