gulp some tips
gulp作为替代grunt的task runner后起之秀,基于nodejs的stream操作模型,大大减少了对磁盘的操作因此大大提高了性能。
gulp error handling
var gulp = require('gulp'); var coffee = require('gulp-coffee'); var concat = require('gulp-concat'); function handleError(error){ console.log(error); this.emit('end'); } gulp.task('coffee',function(){ return gulp.src('src/*.coffee') .pipe(coffee()) .on('error',handleError) .pipe(concat('all.js').pipe(gulp.dest('dist/')); }); gulp.task('watch', ['coffee'], function(){ gulp.watch('src/*.coffee',['coffee']); });
对于gulp.src这类的对glob文件系统的操作,如果文件或者文件夹不存在,后续的gulp stream操作默认也不会有任何错误抛出,有时很让人困惑。
其中的解决方案就是使用gulp-expect-file
var coffee = require('gulp-coffee'); var expect = require('gulp-expect-file'); gulp.task('mytask', function() { var files = ['idontexist.html']; return gulp.src(files) .pipe(expect(files)) .pipe(coffee()); });
http://stackoverflow.com/questions/22343591/gulp-silently-failing-no-errors-printed-to-console
下面通过重载gulp.src的方法实现默认将plumber放到gulp stream errorhandlering中
var gulp = require('gulp'); var plumber = require('gulp-plumber'); var gutil = require('gulp-util'); var gulp_src = gulp.src; gulp.src = function() { return gulp_src.apply(gulp, arguments) .pipe(plumber(function(error) { // Output an error message gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.message)); // emit the end event, to properly end the task this.emit('end'); }) ); };
https://www.timroes.de/2015/01/06/proper-error-handling-in-gulp-js/
积小流以汇江海,细微做起