How to run a task ONLY on modified file with Gulp watch

Another option is to used the gulp.watch on("change") option.

gulp
  .watch([config.path.devfolder+"/**/*.png", config.path.devfolder+"/**/*.jpg", config.path.devfolder+"/**/*.gif", config.path.devfolder+"/**/*.jpeg"])
  .on("change", function(path) {
      gulp
        .src(path)
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngcrush()]
        }))
        .pipe(gulp.dest(buildType))
        .pipe(connect.reload());
  });

No need for plugins, this can be achieved with just gulp.watch.

With gulp.watch, you can target the changed file like this.

gulp.watch(["src/**/*"], function (obj) {
 return gulp.src(obj.path, {"base": "src/"})
 .pipe(gulp.dest("dest"));
});

Edit: for Gulp v4.0.2 - Now fixed:

const { watch, src, dest } = require('gulp');

var watcher = watch(["src/**/*"]);
watcher.on('change', function(fileName){
    return src(fileName, {base: 'src/'})
        .pipe(dest('dest'));
});

"gulp-changed" is not a best solution for doing this, because it watch only modified filed in "buildType" folder.

Try gulp-cached instead.


Incremental builds are supported natively in Gulp without any plugins since version 4.0. Here is the example taken from the project README:

const paths = {
  ...
  images: {
    src: 'src/images/**/*.{jpg,jpeg,png}',
    dest: 'build/img/'
  }
}

function images() {
  return gulp.src(paths.images.src, {since: gulp.lastRun(images)})
    .pipe(imagemin())
    .pipe(gulp.dest(paths.images.dest));
}

function watch() {
  gulp.watch(paths.images.src, images);
}