Automatically in grunt(concat & watch)

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 很多时候我们达到了我们以为的极限,不过是因为我们所处的空间限制了我们的能力,而并不代表我们的能力仅仅在此。 ...
    介眉阅读 356评论 2 3
  • 天气开始转凉了,早晚都这么觉得。 有一年秋天出门,看见一辆车驶过,满地的黄叶就这样凭空起舞,打着旋飞起,又打着旋落...
    常二先生阅读 746评论 0 4