gulpgulp-imagemingulp-watch

How can I run a gulp task only on new and changed files?


I'm trying to use gulp-imagemin to optimize images on my project. But I want to run imagemin only when a new image is added, or a current image is changed. And I want to run it only on the new/changed image.

Someone suggested to use the change and add events like this:

gulp.watch( [ 'myfolder/**/*.png', 'myfolder/**/*.svg' ] )
    .on( "change", function(file){
        console.log("change");
        // do imagemin stuff here
    } );

But the "change" event is not called. I also tried with the "add" event with the same results.

My knowledge of gulp is still limited and I can't figure out how to do this one. So how can I run imagemin only on new / changed images?


Solution

  • I managed to figure out a way to make things work.

    gulp.watch( [ 'myfolder/**/*.png', 'myfolder/**/*.svg' ], function (event) {
        switch (event.type)
        {
            case 'added':
            case 'changed':
                gulp.src( event.path )
                    .pipe( imagemin({
                        optimizationLevel: 5,
                        progressive: true,
                        svgoPlugins: [{removeViewBox: false}],
                        use: [pngquant()]
                    }) )
                    .pipe( gulp.dest( strImgDest ) );
                break;
        }
    } );
    

    Is it the best way to do it? I don't know. My question got close to zero attention from the community. But it sure works for me. I hope this will help someone in the future.