问题
Can I use gulp-imagemin plugin with gulp-watch? So, I need to optimize images as soon as they are put into the folder.
Here is a part of my gulpfile.js:
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
gulp.task('default', function() {
gulp.watch('dist/images/**', function(event) {
gulp.run('images');
});
});
// Image files
gulp.task('images', function () {
return gulp.src('src/images/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('dist/images'));
});
回答1:
in your watch task, you're watching image changes in 'dist/images/'.. you should change that to **'src/images/*'
Also in your image task, you're watching only for images directly in the images folder (non recursive). I'd recomment to listen to 'src/images/'**
Your new gulpfile will look like:
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
gulp.task('default', function() {
gulp.watch('src/images/**', function(event) {
gulp.run('images');
});
});
// Image files
gulp.task('images', function () {
return gulp.src('src/images/**')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('dist/images'));
});
Hope that helps ;-)
来源:https://stackoverflow.com/questions/32416485/can-i-use-gulp-imagemin-with-gulp-watch