gulp some tips

世有因果知因求果發表於2015-07-06

  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/