Gulp & ES6 (ES2015)

I’ve been meaning to give ES6 a try for a while now, but the whole Webpack thing really turns me off.  This site is being served over HTTP/2 so there is very little benefit from bundling, and in my mind bundling reduces the ability to cache changing resources.  ES6 however seems to offer quite a few nice features which i’d love to be able to use.  Thankfully Babel compiles ES6/2015 down to browser supported ES5, and there’s a Gulp plugin to make it all happen automatically!

There are a few npm modules we’re going to need:

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

or

$ yarn add --dev babel-cli babel-core babel-preset-es2015 gulp-babel

Babel can be configured through package.json by adding:

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

and in the gulpfile.json can be set up something like:

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

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

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

To test this works, create the src and dist folders, and in the dist folder create es6.js:

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

Run the Gulp default task, and the output file dist/es6.js should be created and look something like:

"use strict";

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