Using ES6 with Gulp

August 08, 2018

Using es6 with gulp image

Today’s article is a short post on using ES6 inside your gulp file. Gulp syntax is nice and short however with the addition of ES6 syntax inside your gulpfile you can make it even shorter and I personally find it much more readable.

Prerequisites

This article assumes that you have some experience with Gulp and npm. To run gulp using ES6 syntax you will need to install the following npm packages.

First, you will need to install gulp locally and globally.

npm i gulp --save-dev && npm install gulp -g

Making your gulpfile ES6

To get the power of ES6 syntax in your guplfile you will need Babel as a dependency in your project and you will also need a preset. I am using es2015 preset.

npm i babel-core babel-preset-es2015 --save-dev

Once these packages have installed you will need to enable the es2015 preset. You can do this in either the package.json file or in a .babelrc file. I tend to go with the package version because it is one less file in my project.

Putting it in your package.json file:

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

Putting it inside your .babelrc file:

{
  "presets": ["es2015"]
}

This is most of the hard work done. Now all you need to do is create or rename your gulpfile to gulpfile.babel.js You can now use ES6 syntax inside of your gulpfile. In the example gulpfile I have prepared I am also using gulp-sass and autoprefixer so if you would like to copy the example you will need to install the following packages

npm i gulp-sass gulp-autoprefixer --save-dev

Below is the example Gulpfile that I have setup. This includes:

  • Import statements
  • String templating
  • Arrow functions
//gulpfile.babel.js
import gulp from 'gulp';
import sass from 'gulp-sass';
import autoprefixer from 'gulp-autoprefixer';

const dirs = {
  src: `./src`,
  dist: `./build`
}

const paths = {
  sassSrc: `${dirs.src}/sass/master.scss`,
  sassWatch: `${dirs.src}/sass/**/*.scss`,
  cssOutput: `${dirs.dist}/styles/`
}

gulp.task('styles', () => {
  return gulp.src(paths.sassSrc)
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(gulp.dest(paths.cssOutput));
});

gulp.task('watch', () => {
  gulp.watch(paths.sassWatch, ['styles']);
});

I use sass in most of my projects so this is usually my starting gulp template when I am using a Gulp. This minimal gulpfile setup with ES6 is available to download on GitHub. If you are having issues try and setup my starter example or contact me.