Can I use gulp-imagemin with gulp-watch?

蓝咒 提交于 2021-02-08 02:10:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!