Prevent errors from breaking / crashing gulp watch

后端 未结 8 885
我在风中等你
我在风中等你 2020-12-12 09:17

I\'m running gulp 3.6.2 and have the following task that was set up from a sample online

gulp.task(\'watch\', [\'default\'], function () {
  gulp.watch([
            


        
8条回答
  •  暖寄归人
    2020-12-12 09:55

    I have implemented the following hack as a workaround for https://github.com/gulpjs/gulp/issues/71:

    // Workaround for https://github.com/gulpjs/gulp/issues/71
    var origSrc = gulp.src;
    gulp.src = function () {
        return fixPipe(origSrc.apply(this, arguments));
    };
    function fixPipe(stream) {
        var origPipe = stream.pipe;
        stream.pipe = function (dest) {
            arguments[0] = dest.on('error', function (error) {
                var state = dest._readableState,
                    pipesCount = state.pipesCount,
                    pipes = state.pipes;
                if (pipesCount === 1) {
                    pipes.emit('error', error);
                } else if (pipesCount > 1) {
                    pipes.forEach(function (pipe) {
                        pipe.emit('error', error);
                    });
                } else if (dest.listeners('error').length === 1) {
                    throw error;
                }
            });
            return fixPipe(origPipe.apply(this, arguments));
        };
        return stream;
    }
    

    Add it to your gulpfile.js and use it like that:

    gulp.src(src)
        // ...
        .pipe(uglify({compress: {}}))
        .pipe(gulp.dest('./dist'))
        .on('error', function (error) {
            console.error('' + error);
        });
    

    This feels like the most natural error handling to me. If there is no error handler at all, it will throw an error. Tested with Node v0.11.13.

提交回复
热议问题