Gulp imagemin skip folder creation if folder already exists

291 views Asked by At

Im new to Gulp but managed to create the following gulpfile.js to minify images that reside in an /image/ folder and output to my /images/optimised/ folder:

const gulp = require('gulp');
const imagemin = require('gulp-imagemin');

function minifyimages() {

    return gulp.src('./images/*')
    .pipe(imagemin())
    .pipe(gulp.dest('images/optimised'))
    verbose: true
}

exports.minifyimages = minifyimages;

If i run the script for the first time it generates the /images/optimised/ folder on its own, which is fine. But if i run it again then it generates an /images/optimised/optimised/ folder.

Is there a way for it to skip the creation of the /optimised/ folder if it already exists?

Thanks

1

There are 1 answers

0
Mark On BEST ANSWER

Try this task:

function minifyimages() {

    return gulp.src('./images/*.+(gif|png)')   // change here
    .pipe(imagemin())
    .pipe(gulp.dest('./images/optimised'))
    verbose: true
}

I added the file extensions to gulp.src (you may have more image types) so that gulp is not looking into the optimized folder at all. And thus optimizing those as well, with their folder structure.