Alex
Alex

Reputation: 2053

Gulp duplicate image and convert to webp

I have added a webp conversion to my images task in Gulp. It does what it says on the tin and converts the image. What i actually want to achieve is a duplicate webp version of the image, not replace it.

My task is as follows;

gulp.task('images', function() {
    return gulp.src(config.img)
        // Only optimize changed images
        .pipe(plugins.changed(config.dist.img))

        // Imagemin
        .pipe(plugins.imagemin({
            optimizationLevel: 3,
            progressive: true,
            svgoPlugins: [{
                removeViewBox: false
            }]
        }))

        .pipe(webp())

        // Set destination
        .pipe(gulp.dest(config.dist.img))

        // Show total size of images
        .pipe(plugins.size({
            title: 'images'
        }));
});

I am assuming that the conversion needs to happen on a duplicate of the original, rather than the original itself.

I am new to Gulp, so just getting my head round the process.

Everything else in the process is exactly as it should be.

Upvotes: 3

Views: 1263

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30564

The gulp-clone plugin allows you to perform operations on a copy of a file and restore the original afterwards:

gulp.task('images', function() {
    var sink = plugins.clone.sink();  // init sink

    return gulp.src(config.img)
        // Only optimize changed images
        .pipe(plugins.changed(config.dist.img))

        // Imagemin
        .pipe(plugins.imagemin({
            optimizationLevel: 3,
            progressive: true,
            svgoPlugins: [{
                removeViewBox: false
            }]
        }))

        .pipe(sink)        // clone image
        .pipe(webp())      // convert cloned image to WebP
        .pipe(sink.tap())  // restore original image

        // Set destination
        .pipe(gulp.dest(config.dist.img))

        // Show total size of images
        .pipe(plugins.size({
            title: 'images'
        }));
});

Upvotes: 2

Related Questions