How do you watch multiple files, but only run task on changed file, in Grunt.js?

前端 未结 7 1863
盖世英雄少女心
盖世英雄少女心 2020-12-01 00:12

In learning how to use grunt, I am trying to make a simple coffee-script watcher/compiler. The problem is, if I tell the watch task to watch several files, and

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 00:47

    I got this working when compiling my less files. You should be able to mess with this configuration a little bit to git it working with the coffeescript plugin. The portion of interest is the grunt.event.on('watch', ...). In this event handler I'm updating the files property in the less command to only contain the changed file.

    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']);
    };
    

提交回复
热议问题