Gulp has been giving me a lot of trouble since the day we met. Basically because he breaks his watch whenever he smells a bit of error in JavaScript. This is a serious pain in the ass, since with the site I’m working on, I’ll have to restart the server in Terminal, re-login, and click to the page I was previously on. Three additional steps for a minor change. No fun.
This is how to tame him.
I tried a lot of ways, and found this post extremely helpful. To be straight, what we want is to add an error handler for the error thrown. To do this, we need two things. a) an error handler and b) to find the line that throws the error, in Gulp tasks.
First, for the error handler, do this. Later we’ll need to require “gulp-util”.
npm install gulp-util --save-dev
Now, let’s go find the line that’s causing trouble:
For example, my crash-and-break error log was:
[11:01:58] gulp-inject 5 files into index.less. [11:01:58] Finished 'styles' after 48 ms [11:01:58] Starting 'inject'... stream.js:94 throw er; // Unhandled stream error in pipe.
Where did it slip and crash? On the task “inject”. This is where I’m going to dig. Below is the “inject” task:
Import the utility at the top of this file:
var gutil = require('gulp-util');
Normally the line that throws error looks like this:
gulp.src('...') .pipe(functionThatMightThrowAnError()) .pipe(...);
We need to append an error handler after the functionThatMightThrowAnError:
gulp.src('...') .pipe(functionThatMightThrowAnError()) .on('error', gutil.log) .pipe(...);
In my case it’s the place where the cursor stands. Try it in different places and see where it is.
That’s it! life saving.