Search code examples
javascriptgulp

How to exclude folder in gulp task for images?


I am using Gulp 4 for my frontend projects. I am want to exclude "fav" folder in "img" folder for gulp-imagemin. How can I do this? This is my project structure:

structure

This is my gulpfile.js:

var paths = {
    html: {
        src: "src/**/*.html",
        dest: "dest/"
    },

    styles: {
        src: "src/styles/**/*.sass",
        dest: "dest/styles/"
    },

    scripts: {
        src: "src/js/**/*.js",
        dest: "dest/js/"
    },

    images: {
        src: "src/img/**/*.*",
        dest: "dest/img/"
    }
};

function images() {
    return gulp.src(paths.images.src)
        .pipe(imagemin({
            progressive: true,
            interlaced: true,
            use: [pngquant()],
        }))
        .pipe(svgo())
        .pipe(gulp.dest(paths.images.dest));
}

Thanks and happy coding!


Solution

  • You can also try using gulp-filter:

    const filter = require('gulp-filter');
    
    // function images() {
    gulp.task('images', function () {
    
      // restore option lets us bring back the removed files later
      const f = filter(paths.images.exclude, { restore: true });
    
      return gulp.src(paths.images.src)
    
        // filter out, remove, files in the fav directory
        .pipe(f)
    
        // do stuff to remaining files (not including fav/*.*)
        .pipe(imagemin({
          progressive: true,
          interlaced: true,
          use: [pngquant()],
        }))
        .pipe(svgo())
    
        // Bring back the files previously removed from the stream
        .pipe(f.restore)
    
        .pipe(gulp.dest(paths.images.dest));
    });
    
    var paths = {
      images: {
        src: "src/img/**/*.*",
        exclude: ["src/img/**/*.*", "!src/img/fav/*.*"],
        dest: "dest/img/"
      }
    };
    
    gulp.task('default', ['images']);
    

    [Written in gulp3.9 style since that is what I have in my test bed.]

    But I do agree that in this case it may be better to just make two tasks as @Abijeet suggested.