我正在尝试使用grunt-contrib-watch来观看我的图像文件夹,并在任何添加/更改的jpgs,gif或png上运行grunt-imageoptim。
我的代码运行正常,可以在新图像上运行imageoptim,只要我不创建任何新文件夹。显然这已在最近的版本中得到修复,但我对Grunt很新,所以它可能是我缺少的基本内容。我已经通过一个不太具体的通配符看到更改/新文件夹,但是我无法阻止imageoptim在所有文件夹中的所有图像上运行。
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
imageoptim: {
options: {
jpegMini: false,
imageAlpha: true,
quitAfter: true
},
},
watch: {
files: ['images/**/*.jpg', 'images/**/*.png', 'images/**/*.gif'],
tasks: ['imageoptim'],
options: {
spawn: false,
},
},
});
// imageoptim
grunt.loadNpmTasks('grunt-imageoptim');
// grunt watch
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task(s).
grunt.registerTask('default', ['imageoptim']);
var changedFiles = Object.create(null);
var onChange = grunt.util._.debounce(function() {
grunt.config('imageoptim.all.src', Object.keys(changedFiles));
changedFiles = Object.create(null);
}, 200);
grunt.event.on('watch', function(action, filepath) {
changedFiles[filepath] = action;
onChange();
});
};
(底部的功能是在手表更改时运行imageoptim,然后阻止它看到它自己的更改,因为更改会再次进行操作)
答案 0 :(得分:-1)
哎呀,回答了我自己的问题:P我之前(在发布问题之前)在imageoptim中设置src而不是更改watch中的文件。这有效:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
imageoptim: {
options: {
jpegMini: false,
imageAlpha: true,
quitAfter: true
},
},
watch: {
files: ['images/**'],
tasks: ['imageoptim'],
options: {
spawn: false,
},
},
});
// imageoptim
grunt.loadNpmTasks('grunt-imageoptim');
// grunt watch
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task(s).
grunt.registerTask('default', ['imageoptim']);
var changedFiles = Object.create(null);
var onChange = grunt.util._.debounce(function() {
grunt.config('imageoptim.all.src', Object.keys(changedFiles));
changedFiles = Object.create(null);
}, 200);
grunt.event.on('watch', function(action, filepath) {
changedFiles[filepath] = action;
onChange();
});
};