你如何在Grunt.js中观看多个文件,但只在更改的文件上运行任务?

Lan*_*ard 44 javascript node.js gruntjs

在学习如何使用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');
};
Run Code Online (Sandbox Code Playgroud)

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

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

你如何使用grunt 编译更改的文件

小智 15

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

无论哪种方式,如果您有兴趣在项目中尝试开发版本的grunt,请查看我什么时候可以使用开发中的功能'X'?FAQ条目.

  • 是的,所以这不再存在,这仍在讨论中.观看https://github.com/gruntjs/grunt-contrib-watch/issues/14 (6认同)

bla*_*iet 8

编译我的较少文件时,我得到了这个工作.您应该能够使用coffeescript插件轻松搞砸这个配置.感兴趣的部分是grunt.event.on('watch', ...).在此事件处理程序中,我files在less命令中更新属性以仅包含已更改的文件.

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']);
};
Run Code Online (Sandbox Code Playgroud)