Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp Watch only run once

I'm using this Gulp Watch sample: https://github.com/floatdrop/gulp-watch/blob/master/docs/readme.md#starting-tasks-on-events.

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 () {
        gulp.start('build');
    }));
});

When I run it on my Windows 8 machine, it only runs the first time I change a file:

C:\test>gulp watch
[08:40:21] Using gulpfile C:\test\gulpfile.js
[08:40:21] Starting 'watch'...
[08:40:21] Finished 'watch' after 2.69 ms
[08:40:31] Starting 'build'...
Working!
[08:40:31] Finished 'build' after 261 µs

Next time nothing happens. Why?

like image 444
dhrm Avatar asked Mar 25 '15 07:03

dhrm


3 Answers

For me it was adding a "return" to the task:

gulp.task('styles', function(){
 return gulp.src('css/styles.css')
    .pipe(autoprefixer())
    .pipe(gulp.dest('build'));
});
like image 181
Tim Nong Avatar answered Nov 04 '22 20:11

Tim Nong


If you read the documentation closely, you see the following phrase:

You can pass plain callback, that will be called on every event or wrap it in gulp-batch to run it once

So, that's basically the deal with gulp-batch. To constantly watch it, just remove the batch call:

gulp.task('build', function (done) { 
    console.log('Working!'); 
    done();
});

gulp.task('watch', function () {
    watch('app/*.js', function () {
        gulp.start('build');
    });
});

(and add the 'done' callback to build to let Gulp know when you're finished).

Btw... I'm not sure, but I think gulp-watch is meant to not only watch files, but also directly returning a vinyl object. So actually using the built-in gulp.watch should have the same effect:

gulp.task('watch', function () {
    gulp.watch('app/**/*.js', ['build']);
});
like image 22
ddprrt Avatar answered Nov 04 '22 22:11

ddprrt


This appears to be known issue I had the same problem and used the same as ddprrt. The difference was using directory glob (wildcard) as apposed to absolute path.

I changed this:

 gulp.task('watch', function() {
   gulp.watch('sass/shortcutcss/*.scss', ['sass'])
 });

to this:

 gulp.task('watch', function() {
   gulp.watch('sass/**/*.scss', ['sass'])
 });
like image 9
lacostenycoder Avatar answered Nov 04 '22 22:11

lacostenycoder