简体   繁体   中英

GruntJS chaining watch

Considering this sample config(note I've omitted the dependencies to keep it short):

module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        sass: {
            dev: {
                files: {
                    'style.css': 'custom.scss'
                }
            },
        },
        watch: {
            options: {
                livereload: true
            },
            css: {
                files: ['css/sass/**/*.scss'] ,
                tasks: ['sass:dev']
            },
            js:{
                files: ['js/**/*.js']
            },
            html:{
                files: ['templates/**/*.html']
            },
            dontRun:{
                files: ['/randomdir/*'],
                tasks:['randomtask']
            }
        }
    });

    grunt.registerTask('default', ['watch']);
};

How can I start a watch that watches and executes css, js and html , but not dontRun ?

I've tried with:

grunt.registerTask('default', ['watch:css:js:html']);
grunt.registerTask('default', ['watch:css','watch:js','watch:html']);

But both these just execute the first watch, the second and third just don't start.

This is because Grunt can only run tasks in a series. So the watch task can only be ran with one target or all targets.

You can use a dynamic alias task to work around this limitation though:

grunt.registerTask('watchweb', function() {
  // Remove the targets you dont want
  grunt.config('watch.dontRun', null);
  // Then run the watch task after this task is done
  grunt.task.run('watch');
});

Run with grunt watchweb .

Or a more robust and generic solution that works with any config is this:

// Run with: grunt switchwatch:target1:target2 to only watch those targets
grunt.registerTask('switchwatch', function() {
  var targets = Array.prototype.slice.call(arguments, 0);
  Object.keys(grunt.config('watch')).filter(function(target) {
    return !(grunt.util._.indexOf(targets, target) !== -1);
  }).forEach(function(target) {
    grunt.log.writeln('Ignoring ' + target + '...');
    grunt.config(['watch', target], {files: []});
  });
  grunt.task.run('watch');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM