Grunt -观察新的文件夹

Grunt - Watch new folders

本文关键字:文件夹 观察 Grunt      更新时间:2023-09-26

我正在尝试获得grunt-contrib-watch来监视我的图像文件夹,并在任何添加/更改的jpg, gif或png上运行grunt-imageoptim。

下面的代码可以很好地在新图像上运行imageoptim,只要我不创建任何新文件夹。显然这在最近的版本中已经修复了,但我对Grunt很陌生,所以它可能是我缺少的一些基本的东西。我已经让它通过一个不太具体的通配符来查看watch中的更改/新文件夹,但是我不能阻止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();
  });
};