Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the current gulp task which I use in a gulpfile. Path are from a config.json and everything works perfectly:

//Some more code and vars...

gulp.task('watch', function() {
    gulp.watch([config.path.devfolder+"/**/*.png", config.path.devfolder+"/**/*.jpg", config.path.devfolder+"/**/*.gif", config.path.devfolder+"/**/*.jpeg"], ['imagemin-cfg']);
})

//Some more code ...

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

But I still have an issue, the number of images in my project is huge and this task takes ages. I'm looking for a way to run my task ONLY on modified files. If I had an image or modify it, imagemin() will only run on this image, and not on all.

Once again everything is working perfectly fine, but the run time is really long.

Thanks.

like image 714
soenguy Avatar asked May 27 '14 13:05

soenguy


3 Answers

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

Try gulp-cached instead.

like image 145
nktssh Avatar answered Oct 07 '22 16:10

nktssh


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());
  });
like image 37
Brad Berger Avatar answered Oct 07 '22 16:10

Brad Berger


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'));
});
like image 21
lofihelsinki Avatar answered Oct 07 '22 17:10

lofihelsinki