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

不打扰是莪最后的温柔 提交于 2019-11-30 03:49:06

问题


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



来源:https://stackoverflow.com/questions/24296839/why-dont-newly-added-files-trigger-my-gulp-watch-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!