Until gulp 4.0 is released this is actual information
When you pipe one Stream to another and do not attaching on('error')
handler they will unpipe
on every error. This is frustrating, when you have watcher and something like coffeescript
builder. It is pretty easy to put typo in file and breake pipeline forever. To avoid this, you can use gulp-plumber
:
var gulp = require('gulp');
var watch = require('gulp-watch');
var plumber = require('gulp-plumber');
var sass = require('gulp-ruby-sass');
gulp.task('styles', function () {
return gulp.src('scss/*.scss')
.pipe(watch('scss/*.scss'))
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('dist'));
});
Often you want just to launch some tasks (like build
) when something happened to watched files. You can pass plain callback, that will be called on every event or wrap it in gulp-batch
to run it once:
var gulp = require('gulp');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
gulp.task('build', function () { console.log('Working!'); });
gulp.task('watch', function () {
watch('**/*.js', batch(function (events, done) {
gulp.start('build', done);
}));
});
When you want to make actions only on specific events, you can use gulp-filter
and the event
attribute, which is added to all files that were add
, change
or unlink
(per chokidar
's documentation):
var filter = require('gulp-filter');
function isAdded(file) {
return file.event === 'add';
}
var filterAdded = filter(isAdded);
gulp.task('default', function () {
return gulp.src('**/*.js')
.pipe(watch('**/*.js'))
.pipe(filterAdded)
.pipe(gulp.dest('newfiles'))
.pipe(filterAdded.restore())
.pipe(gulp.dest('oldfiles'));
});
Notice: event
property is not added to files that were emitted by emitOnGlob
and emit: 'all'
options, only to files that actually caused the event.
One of the nice features, that can be achieved with gulp-watch
- is incremental build.
When you want to build all files at start and then get only changed files - you can use these snippets:
gulp.task('default', function () {
return gulp.src('**/*.js')
.pipe(watch('**/*.js'))
.pipe(gulp.dest('build'));
});