文章

Watch only some targets at grunt.js

You have a grunt watch config like this:

watch:{
    deploy:{
        files: ["app/**/*.js", "app/**/*.css", "app/**/*.jsp"],
        tasks: ['copyto']
        options: { livereload: true }
    },
    scss:{
        files: ['app/**/*.scss'],
        tasks: ['compass']
    },
    docs:{
        files: ['app/**/*.md'],
        tasks: ['markdown']
    }
}

Say you want to watch for deploy and scss task during development and do docs only when writing documents. But doing grunt watch will watch for all targets. If you try to register:

grunt.registerTask('dev', ['watch:deploy', 'watch:scss']);

It will only run the first task as it is a livereload.

The solution is to write a simple multi-task. First have this in your confg:

watchSome:{
    dev: ['deploy', 'scss'],
    docs: ['docs']
}

And have this multi-task registered

grunt.registerMultiTask('watchSome', 'watch for some targets', function(){
    var originalWatchConfig = grunt.config('watch');
    var newWatchConfig = {};
    this.data.forEach(function(name){
        newWatchconfig[name] = originalWatchConfig[name];
    });
    grunt.config('watch', newWatchConfig);
    grunt.task.run('watch');
});

You can now do a grunt watchSome:dev to watch only deploy and scss at the same time.

*