简体   繁体   中英

How do I delete the regular(jpg, png ) images after converting them to webp usging gulp?

I'm new to gulp. Trying to optimize the images and convert them into webp format. I was able to achieve that using gulp-webp . But it seems there are now two version of the images inside my dist/img folder one is the original and a webp version. So how do I get only the webp not the original one inside my dist/img folder?

Here how my project directories look like:

project
    |-dist
        |-css
        |-img
        |-js
    |-src
        |-css
        |-img
        |-js
    
    gulp.js
    ...

Here is webp conversion function:

function webpImage() {
    return src('dist/img/**/*.{jpg,png}')
        .pipe(imagewebp())
        .pipe(dest('dist/img'))
}

I would first say you should not delete source file, it is ok to keep them. What you want to do is having to different destinations. One of which should be deployed (the compiled, minified and webp for example) and the other should be version and used in your cdci pipelines perhaps.

But then, if you really want to remove the source file, you can use gulp-clean while being in a gulp script.

Your gulp clean script could look like that:

const { src, task } = require('gulp');
const clean = require("gulp-clean");
const logger = require('node-color-log');

function cleanImagesTask() {
    const root = "path/to/images/you/want/to/delete";
    logger.color('yellow').log(`Clean images`);

    return src(root,{allowEmpty: true},{read: false}).pipe(clean({force:true}));
};

const cleanImagesFolder = task('clean:images', cleanImagesTask);
exports.cleanImagesFolder = cleanImagesFolder;

And if you want to deploy in a different dest, could use something similar to:

const { src, dest, task } = require( 'gulp' );
const logger = require('node-color-log');

function copyImagesToDest(callback) {
    const imagesSource = "path/to/your/images/**/*";
    const imagesDestination = "path/to/destination/";

    logger.color('green').log(`Copy images from ${artifactData} to: ${destination}`);

    return src(imagesSource)
            .pipe(dest(destination))
            .on('end', function () { 
                logger.color('green').log(`Copy to: ${destination}`);
                callback(); 
            });
};

const copyImages = task('copy:images', copyImagesToDest);
exports.copyImages = copyImages ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM