我试图让grunt-contrib-watch观看我的图像文件夹,并对添加/更改的jpg,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,然后防止它看到自己的更改作为更改再次执行)

最佳答案

糟糕,回答了我自己的问题: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();
  });
};

关于javascript - Grunt-观看新文件夹,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24191352/

10-12 12:37
查看更多