Grunt imagemin - 观看多个文件/文件夹优化单个文件?

时间:2013-12-17 10:29:28

标签: javascript gruntjs grunt-contrib-watch

是否可以使用grunt-contrib-imagemine和grunt-contrib-watch来观看多个文件/文件夹但只优化单个文件?

我试过这样:( gruntfile的一部分)

imagemin: {
  dist: {
    cwd: 'images/modules',
    files: ['images/modules/**/*.{png,jpg,gif}'],
    dest: 'images/modules'
  }
},

watch: {
   images: {
      files: ['images/modules/**/*.{png,jpg,gif}'],
      tasks: ['imagemin'],
      options: {
      spawn: false,
      }
    }
}

grunt.event.on('watch', function(action, filepath, target) {
  if (grunt.file.isMatch(grunt.config('watch.images.files'), filepath)) {
      grunt.config('imagemin.dist.src', [filepath]);
   }
});

但它不起作用。它返回:

Running "imagemin:dist" (imagemin) task
Verifying property imagemin.dist exists in config...OK
Files: [no src] -> images/modules
Options: optimizationLevel=7, progressive, pngquant=false
Options: optimizationLevel=7, progressive, pngquant=false
Warning: path must be a string

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:7)

基于grunt-contrib-imagemin docs,file属性采用src / dest(键/值)对的对象。

files: {                         // Dictionary of files
    'dist/img.png': 'src/img.png', // 'destination': 'source'
    'dist/img.jpg': 'src/img.jpg',
    'dist/img.gif': 'src/img.gif'
  }

我相信这就是你收到错误的原因。

要做你想做的事,至少我想你想要的,我会在下面给imagemin添加另一个子任务。

imagemin: {
  dist: {
    files: [{
    expand: true,                              // Enable dynamic expansion
    cwd: 'images/modules',                     // Src matches are relative to this path
    src: ['images/modules/**/*.{png,jpg,gif}'],// Actual patterns to match
    dest:'images/modules'                      // Destination path prefix
    }]
  },
  single: {
    cwd: 'images/modules',
    files: 'images/modules/img.png': 'images/modules/img.png', 
    dest: 'images/modules'
  }

},
watch: {
    images: {
      files: ['images/modules/**/*.{png,jpg,gif}'],
      tasks: ['imagemin:single'],
      options: {
      spawn: false,
      }
    }
}

所以上面的watch命令会监视所有匹配文件正则表达式的文件,并执行single主任务的watch子任务。

我认为这是你想要做的事情,但如果没有,你能解释一下吗?