benjaminz
benjaminz

Reputation: 3228

Gulp: How to make gulp automatically delete an output file if the source has been deleted?

I'm using gulp along with gulp-imagemin for some image optimization jobs. And I set up gulp watch to watch for changes once I:

  1. Add new image to the image source folder
  2. Remove an image in the image source folder

So far the first one works pretty well that when a new image is added, gulp runs the task and compresses that new image; however, when I delete an image, gulp doesn't seem to do anything. Am I missing a plugin or some setup here?

Please see my gulpfile below:

// gulpfile.js
var gulp = require('gulp');
var newer = require('gulp-newer');
var imagemin = require('gulp-imagemin');


var imgSrc = 'src/images/**';
var imgDest = 'images';

gulp.task('images', function() {
  return gulp.src(imgSrc)
  .pipe(newer(imgDest))
  .pipe(imagemin({
      optimizationLevel: 5,
      progressive: true,
      interlaced: true
    }))
  .pipe(gulp.dest(imgDest));
});

gulp.task('watch', function() {
  gulp.watch(imgSrc, ['images']);
});

gulp.task('default', ['images', 'watch']);

Upvotes: 2

Views: 1923

Answers (1)

Stephen O'Kennedy
Stephen O'Kennedy

Reputation: 253

Try this:

var gulp  = require('gulp');
var del = require('del');
var imagemin = require('gulp-imagemin');

var imgSrc = 'src/images/**';
var imgDest = 'dist/images';

gulp.task('images', function() {
  return gulp.src(imgSrc)
  .pipe(imagemin({
      optimizationLevel: 5,
      progressive: true,
      interlaced: true
    }))
  .pipe(gulp.dest(imgDest));
});

gulp.task('clean-img', function (cb) {
 return del(imgDest,cb);
 });
gulp.task('watch', function() {
  gulp.watch(imgSrc, ['clean-img','images']);
});

gulp.task('default', ['clean-img','images', 'watch']);  

This will clean out you dist folder and add in the images from the src folder. Unfortunately this approach doesn't work with gulp-newer and will process all your images every time there's a change.

Upvotes: 1

Related Questions