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:

1
2
3
4
|-- 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

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

npm install

Let’s install everything we need

Babel

We need the babel core, CLI and es2015 preset:

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

Gulp

We need gulp and the babel module for gulp.

1
$ 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).

1
2
3
"babel": {
"presets": ["es2015"]
}

Gulp

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

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

Then declare our default task:

1
2
3
gulp.task('default', function () {
});

Then for our task content:

  • Pick up the js files in /src
  • Compile it with babel
  • Put everything in /dist
1
2
3
4
5
6
gulp.task('default', function () {
return gulp.src('src/**/*.js')
.pipe(babel())
.pipe(gulp.dest('dist'));
});

Run the build script

Run the build script using

1
$ gulp

And your compiled files will be in the output folder.

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

1
2
3
4
5
"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.