gulpgulp-watchgulp-imagemin

Gulp imagemin - optimize only one image


This code is working perfectly, it will optimize all images in folder and that is ok if I need to call the task manually using gulp images. But usually I just do gulp watch and for that all images previously added don't need to be reoptimised.

So, how can gulp optimize only the image that was just added to folder, and not all of them?

gulp.task('images', function() {
    gulp.src('images/src/*.{png,jpg,gif}')
    .pipe(plumber(plumberErrorHandler))
    .pipe(imagemin({
        optimizationLevel: 7,
        progressive: true
    }))
    .pipe(gulp.dest('images'))
    .pipe(notify("Images optimized."));
});

gulp.task('watch', function() {
    gulp.watch('images/src/*.{png,jpg,gif}', ['images']);
});

Solution

  • gulp-changed should serve this purpose.

    Basically it compares the files' last-modified property if the source is newer than the destination he passes it down the stream, otherwise it's removed from it.