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

Is it possible to watch multiple files/folders but optimise only a single file using grunt-contrib-imagemine and grunt-contrib-watch?

I tried like this: (part of 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]);
   }
});

But it doesn't work. It returns:

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

Any ideas? Thank you.

Answers:

Answer

Based on the grunt-contrib-imagemin docs the file attribute takes an object of src/dest (key/value) pairs.

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

I believe that is why you are getting the error.

To do what you want, at least what i think you want i would add another subtask to imagemin like below.

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,
      }
    }
}

so the above watch command will watch all files that match the files regex and will carry out the single subtask of the watch main task.

Again i think this is what you want to do but if not could you explain it more?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.