Why don't newly added files trigger my gulp-wa

2020-03-01 18:08发布

问题:

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?

回答1:

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.



回答2:

Adding an extra argument {cwd:'./'} in gulp.watch worked for me:

gulp.watch('src/js/**/*.js',{cwd:'./'},['scripts']);

2 things to get this working:

1 Avoid ./ in the file/folder patterns

2 Ensure ./ in the value for cwd

Good Luck.

Ref:- https://stackoverflow.com/a/34346524/4742733