Gulp不断产生图像

时间:2016-09-24 14:23:33

标签: javascript node.js performance gulp

我正在使用以下代码在上传时生成不同大小的图片,但下面的脚本每次都会生成图像而不管上传的文件是否上传,我在下面的代码中做错了什么?

const gulp = require('gulp'),
  imageresize = require('gulp-image-resize'),
  imagemin = require('gulp-imagemin'),
  pngquant = require('imagemin-pngquant'),
  path = require('path'),
  rename = require('gulp-rename'),
  paths = {
    src: 'uploads/*/*.*'
}

// create an array of image groups (see comments above)
// specifying the folder name, the ouput dimensions and
// whether or not to crop the images
const images = [
    { folder: '100x100', width: 100, height: 100, crop: true },
    { folder: '800x330', width: 800, height: 500, crop: true }
];


// images gulp task
gulp.task('images', function () {

    // loop through image groups
    images.forEach(function(type){

        // build the resize object
        var resize_settings = {
            width: type.width,
            crop: type.crop,
            // never increase image dimensions
            upscale : false
        }
        // only specify the height if it exists
        if (type.hasOwnProperty("height")) {
            resize_settings.height = type.height
        }

        gulp

        // grab all images from the folder
        .src(paths.src)

        // resize them according to the width/height settings
        .pipe(imageresize(resize_settings))

        // optimize the images
        .pipe(imagemin({
            progressive: true,
            // set this if you are using svg images
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        //rename the destination file
        .pipe(rename(function(file) {
          file.dirname = file.dirname+"/"+type.folder;
        }))

        // output each image to the dest path
        // maintaining the folder structure
        //paths.dest+type.folder
        .pipe(gulp.dest(function(file){
          return path.join(path.dirname(file.path), "../", "../");
        }));
    });
});

gulp.task('watch', function(){
     gulp.watch('uploads/**', ['images']);
})

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

2 个答案:

答案 0 :(得分:1)

这是因为gulp手表的工作方式。 您可以参考以下内容:use gulp-chached

答案 1 :(得分:0)

我已经更新了我的代码以使用“gulp-once”,与其他lib相比效果更好。