Compiling ES6 with Gulp and Babel

The current stable of module bundlers like Webpack and Browserify are incredible tools that make creating performant and cutting-edge web apps a breeze, but they do tend to be somewhat difficult to set-up and configure, using rather arcane syntax and concepts. We all want to use modern, cutting-edge Javascript, but for a small project or a proof of concept are they really worth the overhead if all we want is to be able to write in ES6? Perhaps there could be another way…

The good news is that there is another way – using Gulp!

Gulp may have been a bit overshadowed by recent advances in the front-end landscape, but it remains a super easy and convenient way to manage the linting, minification etc. of your source code. That said, how can we use Gulp to compile our ES6 and beyond into browser-compliant ES5?

Luckily, there is an excellent NPM package called gulp-babel which will do the heavy lifting for us. This method is a simple way of implementing Javascript compilation which can offer huge benefits for small projects and proofs of concept and should take only a few minutes to add to your stack.

Wait, what is ES6 and why?

ES6/ES2015 is the current hotness* of ECMAScript (Javascript), and adds some new and juicy functionality for us to play with. This is what the big boys in the industry all use, but sadly for the rest of us, browser support isn’t quite there yet ( IE >:[ ). This is where Babel comes in. Babel is a Javascript compiler which takes ES6/ES7 and beyond and converts them to Javascript which we can safely use in production, even for those pesky legacy browsers. Great!

* ES7 and ES8 are more recent 🙂 But these are not yet widely supported or so well-known. The space-age sounding ES Next refers to upcoming, proposed changes to the language, and is likely to depart from the current method of yearly, iterated releases.

Popular additions from ES6 which you may recognise…

  • const/let
  • ‘fat’ arrow functions
  • template literals

So, how do we use gulp-babel?

The gulp-babel plugin is pretty simple to use and just requires us to add a new pipe for Babel as we would do for any other gulp plugin i.e. for SCSS compilation, sourcemaps etc. The only caveats to that statement are that we will also need a relevant Babel preset and a browser polyfill.

Requirements:

  • Gulp itself!
  • The gulp-babel plugin
  • Babel core
  • Babel preset  – these are editable rulesets which define what level of code Babel should compile down to e.g. ES2015, ES2016 etc.
  • A browser polyfill plugin – this will emulate a full ES6 environment and fill any holes created by Babel optimising for Node.

Install gulp-babel and the babel polyfill.

Make sure that you have Node, NPM and Gulp installed and up-to-date and then fire up your terminal and run:
npm install --save-dev gulp gulp-babel @babel/core @babel/preset-env babel-polyfill
The preset-env package is important because this is what specifies our compilation ruleset. You could specifically call in the preset you desire (e.g. ‘babel-preset-es2017’ etc.), but by using the automatic package here, we can automatically include all the polyfills and transforms for the very latest ES versions. To then ensure that we are compiling down to the correct compatibility level, we will specify our desired preset in our gulpfile configuration.

Configure your gulpfile to tell Babel to compile the JS.

Make sure to pass in the polyfill script with your personal scripts, and then pipe your JS through Babel.

var gulp = require('gulp');
var babel = require('gulp-babel');
---
gulp.task('scripts', function() {
    return gulp.src(
      [
      'node_modules/babel-polyfill/dist/polyfill.js',
      'js/*.js'
      ])
      .pipe(babel({
        presets: ['@babel/preset-env']
      }))
      .pipe(gulp.dest('compiled'))
});

Our preset here is set to the smart preset provided by Babel, but you can also pass in config here to target specific ES rulesets or browser versions. Check out the Babel docs for more info about this. Be aware that not all config options work with the gulp-babel package though, so a little trial and error is required 🙂

Example output

For example, the below ES6 function for saying hello to the person whose name is passed as an argument would compile down to ES5 as follows:

ES6:

const hello = (name) => {
    return `hello ${name}`;
};

Babel output:
var hello = function hello (name) {
    return "hello " + name;
};

That was easy! 🙂 

You’ve learnt how to inject Babel into your Gulp workflow as a method of compiling ES6. Now, try playing around with some different configuration options and get practising with all the new and exciting methods available to you in modern Javascript – async/await, spread operators etc…

Get in contact if you get stuck or need any other web development advice.

Updated 10/12/2020 to use updated @babel packages. Thanks to Sebastian Bolt from JR Marketing GmbH for the heads up.

Further Reading:

Latest blog posts

Change is here! Pixel Pixel launches its new website.

You've probably noticed by now, but our site has had a bit of a rebuild - here's ...

Christmas Business Update

As we prepare to say goodbye to 2021 and welcome in the new year we wanted to share some equally ...

Our Work

We evolved an existing forms system to become an integral part of GWR’s business operations.

We created a website for Europe’s leading product management training provider.

Contact us