Automatically
One of the most popular Grunt plugins is grunt-contrib-watch
( http://gswg.io#grunt-contrib-watch ) as it allows us to place Grunt in the
background and have it automatically run our tasks as they're needed. Written by
Kyle Robinson Young, the watch task instructs Grunt to watch a particular set of files
for changes and execute a particular task or set of tasks in response. In the following
example, we'll watch our source files, and then run our JavaScript concatenation task
concat whenever any of these files are changed:
//Code example 13-watch
module.exports = function(grunt) {
// Load the plugins that provide the "concat" and "watch" tasks.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
// Project configuration.
[ 70 ]Chapter 3
grunt.initConfig({
srcFiles: ["src/a.js", "src/b.js", "src/c.js"],
concat: {
target1: {
files: {
"build/abc.js": "<%= srcFiles %>"
}
}
},
watch: {
target1: {
files: "<%= srcFiles %>",
tasks: ["concat"]
}
}
});
// Define the default task
grunt.registerTask('default', ['concat', 'watch']);
};
At the top of our Gruntfile.js file, we'll load both the plugins that provide the
concat and watch tasks. We will then configure them using a shared srcFiles
property. This means we can modify our source files once, and all tasks using this set
of files will stay current. This helps to keep our build DRY ( http://gswg.io#dry ) by
creating a single source of truth. All targets of the watch task (only target1 in this
case) require a tasks property that should specify a list of tasks to run when one of
the target's files are changed. Finally, we'll provide a default task that runs concat
followed by watch . Running grunt at this point should produce:
grunt
Running "concat:target1" (concat) task
File "build/abc.js" created.
Running "watch" task
Waiting...
At this point, our watch task is running and is Waiting... for one of our files to
change; so if we modify and save src/b.js , we should see the following appended
to our output:
OK
>> File "src/b.js" changed.
Running "concat:target1" (concat) task
[ 71 ]Using Grunt
File "build/abc.js" created.
Done, without errors.
Completed in 0.648s at Tue Sep 17 2013 21:57:52 GMT+1000 (EST)
Waiting...
Our concat task was run, and our watch task is Waiting... again, ready for more
changes. Since we are watching our source files, we can now minimize our terminal
window and continue with our development workflow, knowing that Grunt is
running in the background, taking care of the "grunt" work for us.
网友评论