2016-09-24 57 views
0

我正在使用下面的代碼來生成上傳時發生的不同大小的圖像,但下面的腳本每次都生成圖像,而不管上傳文件或不上傳文件夾,我是否在下面做了任何錯誤碼?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']); 

回答

0

我已更新我的代碼以使用「gulp-once」,與其他庫相比,它更好地工作。