gulpgulp-imageminimagemingulp-watch

Why don't newly added files trigger my gulp-watch task?


I have a gulp task which uses gulp-imagemin to compress images. When I add new files to this directory I'd like for this task to compress them as well. I read that gulp.watch doesn't trigger on new files and that I should try gulp-watch so I used it like so;

gulp.task('images', function() {
  watch({glob: './source/images/*'}, function (files) {
    return files
      .pipe(plumber())
      .pipe(imagemin({
        progressive: true,
        interlaced: true
      }))
      .pipe(gulp.dest('./www'));
  });
});

This works the same as gulp.watch on the first run, but when I add a new image to the directory nothing happens. If I overwrite an existing file however, it DOES run the task again, so it does behave differently.

The documentation on gulp-watch called this "Batch Mode" and said I could also run the task on a per-file basis, so I tried this way too;

gulp.task('images', function() {
  gulp.src('./source/images/*')
    .pipe(watch())
    .pipe(plumber())
    .pipe(imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('./www'));
});

But nothing changed. Why isn't adding files to my image directory triggering the task?


Solution

  • Most likely such kind of questions are redirected to gaze package and its internal processes, that runs complicated watching procedures on your OS. In this case you should pass images/**/* to glob option, so gaze will watch all (including new) files in images directory:

    var gulp = require('gulp');
    var watch = require('gulp-watch');
    var imagemin = require('gulp-imagemin');
    
    gulp.task('default', function() {
        watch({glob: 'images/**/*'}, function (files) {
          files.pipe(imagemin({
            progressive: true,
            interlaced: true
          }))
          .pipe(gulp.dest('./www'));
        });
    });
    

    But this fill not fix case, when you have empty images directory. If you want to watch them, pass ['images', 'images/**/*'] to glob, and it will watch directory, that initially empty.

    P.s. also you dont need gulp-plumber in this case, because watch will rerun function, that uses imagemin every time, even when imagemin pops an error.