【问题标题】:How do you watch multiple files, but only run task on changed file, in Grunt.js?您如何在 Grunt.js 中查看多个文件,但仅在更改的文件上运行任务?
【发布时间】:2012-08-21 21:23:53
【问题描述】:

在学习如何使用grunt 时,我正在尝试制作一个简单的咖啡脚本观察器/编译器。问题是,如果我告诉watch 任务监视几个文件,其中一个文件发生变化,它会将所有文件传递给coffee 命令。这意味着当您更改 1 个文件时,它将重新编译 所有 与 src 模式匹配的文件。相反,我只想重新编译与src 模式匹配的已更改的单个文件。

这里是grunt.js:

module.exports = function(grunt) {
  grunt.initConfig({
    coffee: {
      app: {
        src: ['test/cases/controller/*.coffee'],
        dest: 'tmp',
        options: {
          bare: true,
          preserve_dirs: true
        }
      }
    },
    watch: {
      files: ['<config:coffee.app.src>'],
      tasks: ['coffee:app']
    }
  });

  grunt.loadNpmTasks('grunt-coffee');
  grunt.registerTask('default', 'coffee');
};

这是使用grunt-coffee,基本上是这样的:https://gist.github.com/2373159。

当我运行grunt watch 并将文件保存在test/cases/controller/*.coffee 中时,它会编译所有 匹配的文件(将它们放入tmp/*)。

您如何只使用 grunt 编译 更改的文件?

【问题讨论】:

    标签: javascript node.js gruntjs


    【解决方案1】:

    即将推出的(目前正在开发中的)v0.4.0a grunt 具有 grunt.file.watchFiles 对象,它是专门为此目的而设计的。 grunt-coffee 插件可能已经添加了对此功能的支持,我不确定。

    无论哪种方式,如果您有兴趣在您的项目中尝试开发中的 grunt 版本,请查看When will I be able to use in-development feature 'X'? 常见问题解答条目。

    【讨论】:

    【解决方案2】:

    我在编译较少的文件时得到了这个工作。您应该能够稍微弄乱这个配置,以便将它与咖啡脚本插件一起使用。感兴趣的部分是grunt.event.on('watch', ...)。在此事件处理程序中,我将更新 less 命令中的 files 属性以仅包含更改的文件。

    path = require('path');
    
    module.exports = function(grunt) {
    
      // Project configuration.
      grunt.initConfig({
    
        pkg: grunt.file.readJSON('package.json'),
    
        less: {
          development: {
            options: {
              paths: ["./library/less"],
            },
            files: [
              { src: "./library/less/bootstrap.less", dest: "./library/css/bootstrap.css"},
              { src: "./library/less/app.less", dest: "./library/css/app.css"}
            ]
          }
        },
    
        watch: {
          styles: {
            files: "./library/less/*",
            tasks: ["less"],
            options: {
              nospawn: true,
            },
          },
        },
      });
    
      // Event handling
      grunt.event.on('watch', function(action, filepath){
        // Update the config to only build the changed less file.
        grunt.config(['less', 'development', 'files'], [
          {src: filepath, dest: './library/css/' + path.basename(filepath, '.less') + '.css'}
        ]);
      });
    
      // Load the plugins
      grunt.loadNpmTasks('grunt-contrib-less');
      grunt.loadNpmTasks('grunt-contrib-watch');
    
      // Tasks
      grunt.registerTask('default', ['watch']);
    };
    

    【讨论】:

    • 此方法不适用于building files dynamically。有什么解决方法吗?
    • @blachniet:这太棒了!但我仍然有一个问题——也许你知道答案。是否可以覆盖选项的单个属性?例如,在监视事件处理程序中,我使用“grunt.config(['sftp', 'widgets', 'options.srcBasePath'], file_path);”。我希望使用我已经在 sftp 配置中设置的选项,但向其中添加一个键值对。那可能吗?上面的代码没有任何反应。使用“grunt.config(['sftp', 'widgets', 'options'], {"srcBasePath:":file_path});"所有其他选项都被覆盖...
    • @blachniet: 没关系^^ - grunt.config(['sftp', 'widgets', 'options', 'srcBasePath'], file_path);用于设置单个键值对。 ;)
    【解决方案3】:

    这些答案都不适合我。如果有人感兴趣,这是我的解决方案(我知道我回答这个问题有点晚了)。

    https://gist.github.com/ryansmith94/8569178

    【讨论】:

    • 发布正确答案永远不会太晚——事情总是在变化。
    【解决方案4】:

    在这个issue 中,Kyle Robinson 建议使用watchevent。将监视任务nospawn 属性设置为true 以使其工作非常重要。我修改了他的解决方案以选择性地运行任务:

    grunt.event.on('watch', function(action, filepath) {
        if (minimatch(filepath, grunt.config('watch.stylesheets.files'))) {
            grunt.config('compass.dist.options.specify', [filepath]);
        }
    
        if (minimatch(filepath, grunt.config('watch.scripts.files'))) {
            var uglifySrc = filepath.replace(grunt.config('uglify.dist.cwd'), '');
            grunt.config('jshint.dist.src', [filepath]);
            grunt.config('uglify.dist.src', [uglifySrc]);
        }
    });
    

    这里是完整的解决方案:https://gist.github.com/luissquall/5408257

    【讨论】:

      【解决方案5】:

      https://github.com/tschaub/grunt-newer 看起来完全适合类似的任务:

      将 Grunt 任务配置为仅使用较新的文件运行。

      概要:较新的任务将配置另一个任务以使用 src 运行 a) 比 dest 文件新或 b) 比上一个文件新的文件 成功运行(如果没有 dest 文件)。请参阅下面的示例 以及更多细节。

      您可以轻松地为任何任务添加前缀。在你的情况下:

        grunt.loadNpmTasks('grunt-newer');
        grunt.registerTask('default', 'newer:coffee');
      

      【讨论】:

      • 较新的插件对我来说非常好用……而且速度很快。
      【解决方案6】:

      Grunt 0.4 的新功能是更多的命名任务

      让我们举个例子!

      watch: {
          package1: {
              files: [
                  './modules/package1/**/*.coffee'
              ],
              tasks: ['coffee:package3']
          },
          package2: {
              files: [
                  './test_packages/package2/**/*.coffee'
              ],
              tasks: ['coffee:package3']
          },
          package3: {
              files: [
                  './test_packages/package3/**/*.coffee'
              ],
              tasks: ['coffee:package3']
          },
      }
      

      要运行所有这些监视任务,只需执行 grunt.registerTask('default', ['myInitialBuild', 'watch']);

      myInitialBuild 是任何初始构建(所有文件),然后在每个包上监视它。实际上,您可以对每个文件都这样做,但这听起来很糟糕。

      【讨论】:

        【解决方案7】:

        任务 grunt-contrib-watch 现在支持这个。

        https://npmjs.org/package/grunt-contrib-watch -> 查找“按需编译文件”

        grunt.initConfig({
          watch: {
            scripts: {
              files: ['lib/*.js'],
              tasks: ['jshint'],
              options: {
                nospawn: true,
              },
            },
          },
          jshint: {
            all: ['lib/*.js'],
          },
        });
        
        // on watch events configure jshint:all to only run on changed file
        grunt.event.on('watch', function(action, filepath) {
          grunt.config(['jshint', 'all'], filepath);
        });
        

        这应该可以防止任务在每次发生变化时编译所有文件。

        【讨论】:

        • grunt.config(['jshint', 'all'], filepath);设置的新值多久生效?任务完成后是否恢复到之前的设置?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-15
        • 1970-01-01
        • 1970-01-01
        • 2013-05-23
        相关资源
        最近更新 更多