Search code examples
gulpgulp-watchrun-sequencegulp-load-plugins

Gulp watch runs only once


I'm trying to finish my gulpfile.js but I'm running into a problem with "gulp watch". When I set my watcher to run, it detects changes and run the assigned task, but only once. The next changes on the files don't trigger the tasks anymore. I don't know why, but my watcher is working just once.

I believe the watcher is not realizing the tasks it triggered are finished. Or, maybe it's something to deal with the lazy loading or run-sequence plugins I'm using...

var
  gulp = require('gulp'),
  plugins = require('gulp-load-plugins')({
    DEBUG: true
  });
plugins.runSequence = require('run-sequence');

gulp.task('watch',function(){
  gulp.watch('public/**/*.+(css|js)',['buildEspecifico']);
});

gulp.task('buildEspecifico',function(callback){
  return plugins.runSequence(
    ['deletarMainMin'],
    ['agruparJS','agruparCSS']
  );
});

'deletarMainMin','agruparJS','agruparCSS' are other tasks defined in the same gulpfile.

Thanks in advance!

Cheers,

Fabio.


Solution

  • I believe the watcher is not realizing the tasks it triggered are finished.

    Yes, that is exactly it. In your buildEspecifico task you accept a callback. That means gulp will not consider your buildEspecifico task to have finished unless you invoke that callback.

    Since you don't invoke callback the buildEspecifico task never actually finishes once it runs. And because your buildEspecifico task is technically still running gulp doesn't start the task again when a file changes.

    The solution is to pass callback to runSequence. It will invoke the callback when all of your tasks in the sequence have finished.

    gulp.task('buildEspecifico',function(callback){
      return plugins.runSequence(
        ['deletarMainMin'],
        ['agruparJS','agruparCSS'],
        callback
      );
    });
    

    Alternatively you can also just leave out the callback altogether:

    gulp.task('buildEspecifico',function(){
      return plugins.runSequence(
        ['deletarMainMin'],
        ['agruparJS','agruparCSS']
      );
    });
    

    Obviously you have to make sure that the tasks deletarMainMin, agruparJS, agruparCSS themselves finish, so either call or leave out the callback in those tasks too.