How to Prevent Less Errors Stopping Gulp Watch

Comments

A gulp watch task will stop as soon as you have a Less error. Here’s I how prevented that.

A simple gulp less task

Here is a simple gulp less task that runs manually by typing gulp css:less:

1
2
3
4
5
6
7
8
9
10
11
12
var less = require("gulp-less");

gulp.task(css:less", function (cb) {
   var lessArgs = {
          // fill in as appropriate
        };

   return gulp
  .src(“./less/**/*.less")
  .pipe(less(lessArgs))
  .pipe(gulp.dest("dist/"));
});

A simple “gulp watch” task

Here is a simple watch version of the task - it will watch less files, and rerun the task whenever a file is changed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var less = require("gulp-less");
var watch = require("gulp-watch");

gulp.task("css:watch", function (cb) {
  var lessArgs = {
      // fill in as appropriate
    };

  return gulp
  .src(./less/**/*.less")
  .pipe(watch(“./less/**/*.less"))
  .pipe(less(lessArgs))
  .pipe(gulp.dest("dist/"));
});

The gulp-less plugin documentation doesn’t help

The gulp-less plugin documentation states

By default, a gulp task will fail and all streams will halt when an error happens.To change this behavior check out the error handling documentation here

But don’t waste your time installing the stream-combiner2 plugin - it doesn’t work.

Plumber, which I came across when googling for the issue (you’ll probably end up in this github issue sooner or later if you google for this) didn’t help either.

How to stop “gulp watch” dying when on a Less or Sass error

The solution that worked for me was to create a function which handles the error and make the function emit the error. Then attach directly to the less task:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var gutil = require("gulp-util");
var less = require("gulp-less");
var taskName = css:less";
var onError = function (err) {
    gutil.log(gutil.colors.red("ERROR", taskName), err);
    this.emit("end", new gutil.PluginError(taskName, err, { showStack: true }));
  };

gulp.task(taskName, function jsLint() {
  var lessArgs = {
      // fill in as appropriate
    };

  return gulp
  .src(“./less/**/*.less")
  .pipe(watch(./less/**/*.less"))
  .pipe(less(lessArgs).on('error', onError))
  .pipe(gulp.dest("dist/"));
});

In the example above, the function is onError - is the “this.emit” that does the magic. gutil.log is only eye candy. The onError function is connected to less with .on(“error”, onError). And that’s all there is to it.

Comments