From Gulp 3 to Gulp 4

Published April 20, 2019

Back in late 2018, Gulp 4 was (finally) released as the default version installed with npm install gulp. I’ve been using Gulp for several years & Gulp 4 introduces some new concepts with a non-backwards-compatible API changes. Let’s go over converting a simple Gulpfile that compiles & autoprefixers SCSS to CSS on file change.

Here’s the starting Gulpfile v3 file:

var gulp = require("gulp"),
    plugins = require("gulp-load-plugins")();

// Compile and autoprefix the SCSS
gulp.task("build:sass", function () {
  return gulp
    .src("sass/*.scss")
    .pipe(plugins.plumber())
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest("css/"));
});

// Watch for changes and rebuild CSS
gulp.task("watch", function () {
  gulp.watch("sass/**.scss", ["build:sass"]);
});

// Set default task
gulp.task("default", ["watch"]);

After removing Gulp 3 & adding Gulp 4, if I try to run gulp I get the following error:

AssertionError [ERR_ASSERTION]: Task function must be specified

Since the API changed from gulp.task(name, deps, func) to gulp.task(name, gulp.{series|parallel}(deps, func)). Let’s change it:

gulp.task("default", gulp.series("watch"));

After running gulp again, there’s a different error:

Error: watching sass/**.scss: watch task has to be a function (optionally generated by using gulp.parallel or gulp.series)

gulp.watch is expecting a function for the task(s). We can use gulp.series like above:

gulp.watch("sass/**.scss", gulp.series("build:sass"));

After that, the Gulpfile is working as it was with v3. However, let’s take it one step further & ES6-ify it and use conventions from the Gulp docs:

const { src, dest, watch, series } = require("gulp")
const plugins = require("gulp-load-plugins")()

// Compile and autoprefix the SCSS
const sass = () => {
  return src("sass/*.scss")
    .pipe(plugins.plumber())
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(dest("css/"));
}

// `export` makes it public (from the CLI)
exports.sass = sass

// Watch for changes and rebuild CSS (Note single task)
const watcher = () => watch("sass/**.scss", sass)

// `export` makes it public (from the CLI)
exports.watch = watcher

// Set default task
exports.default = series(watcher)

In general, the conventions follow using export to export tasks to be available from the CLI. ES6 destructuring allows functions from gulp to be accessed independent (e.g. series() vs gulp.series()).

Despite Gulp v4 taking a few years to officially release, there’s a fair amount of (breaking) changes versus v3. Knowing the basics of the API changes, most Gulpfiles can ported in an hour or two of work. Plus, you get the niceties like improved chaining of tasks (series & parallel).

P.S. The code is available on GitHub: Pinjasaur/gulp-3-to-4

Last modified April 20, 2019  #js   #dev   #gulp 

🔗 Backlinks

← Newer post  •  Older post →