让gulp watch出错时不退出

gulp是我编译sass与js的不二利器(比webpack好用),但这几天突然发现,gulp watch时,通常莫名其妙的退出,然后实时编译就断了,然后你还在奇怪为什么改了样式没反应。

gulp实现编译sass时,容易频繁出错,比如你写了个ma没按tab就手贱按了保存,sass一编译,不认识ma,就报错了,如果此时导致watch被退出,那后续编译就中断了。报错导致退出,很正常,但如果报错很频繁又每次都导致退出,那人都要疯了。

于是我只有找一下如何让gulp的watch任务在出错时不自动退出。

很简单,我直接说结论

在gulp的task里,加入onerror监听,在监听函数中,处理错误并触发end。代码如下:

function swallowError(error) {
    // If you want details of the error in the console
  console.error(error.toString())

  this.emit('end')
}
gulp.task('sass', function(){
    return gulp.src('./source/sass/*.scss')
        .pipe(sass())
        .on('error', swallowError)
        .pipe(gulp.dest('./css'));
    });
gulp.task('default', function(){
    gulp.watch('./source/sass/*.scss',['sass']);
    gulp.watch('./source/js/*.js',['js']);
});

注意,on(‘error’)并不是加在watch任务的后面,而是加在watch到变化时要执行的任务的里面。

这样处理一下后,就能看到错误,而watch又不会退出,再次修改文件后,编译就又自动继续了:

原文:http://t.cn/RiHSozV

原文地址:https://www.cnblogs.com/tgxh/p/6859792.html