Watching Files for Changes

We’ve set up a ton of tasks so far, but every time we make a change to a file we have to run Grunt manually. And we really should never have to do anything manually when it comes to task management. Let’s use the grunt-contrib-watch plug-in to watch files for changes and run the appropriate tasks.

Install the plug-in first:

 
$ ​npm install grunt-contrib-watch --save-dev

To configure this plug-in, we specify a target, the files to watch, and the Grunt tasks that should run when those files change. For our JavaScript files, we’ll actually want to watch the CoffeeScript files for changes. When those files change, we’ll need to run the coffee, concat, and uglify tasks. Then we’ll want to watch the CSS files for changes and run the sass and cssmin tasks. So first, let’s set up the configuration to watch the JavaScript files:

workflow/markdown/Gruntfile.js
 
grunt.loadNpmTasks(​'grunt-contrib-watch'​);
 
 
grunt.config(​'watch'​, {
 
scripts: {
 
files: [​'coffeescripts/**/*.coffee'​],
 
tasks: [​'coffee'​, ​'concat:scripts'​, ​'uglify'​],
 
 
options: {
 
spawn: false
 
}
 
},
 
});

And then, inside of that configuration block, we’ll add another target for the Sass files:

workflow/markdown/Gruntfile.js
 
styles: {
 
files: [​'sass/**/*.scss'​],
 
tasks: [​'sass'​, ​'cssmin'​],
 
options: {
 
spawn: false
 
}
 
},

To use this, we employ the grunt watch command. Unlike other tasks, Grunt doesn’t return to the command line. Instead, it stays running in a loop, watching files for changes. Open one of the Sass files or the CoffeeScript files, make a change, save the file, and watch the changes happen.

To stop watching, press Ctrl-C.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.30.162