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

Grunt imagemin - watch multiple files/folders optimise single file?

本文关键字:文件 文件夹 优化 单个 imagemin- 观察 Grunt      更新时间:2023-09-26

是否可以监视多个文件/文件夹,但使用grunt contrib imagemine和grunt contib 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

有什么想法吗?非常感谢。

基于grunt contrib imagemin文档,file属性采用src/dest(key/value)对的对象。

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命令将监视与文件regex匹配的所有文件,并将执行CCD_ 2主任务的CCD_。

我再次认为这是你想做的,但如果不能,你能解释更多吗?