Run predefined tasks whenever watched file patterns are added, changed or deleted
Getting Started
If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
npm install grunt-contrib-watch --save-dev
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
grunt.loadNpmTasks('grunt-contrib-watch');
Watch task
Run this task with the grunt watch command.
Settings
There are a number of options available. Please review the minimatch options here. As well as some additional options as follows:
files
Type: String|Array
This defines what file patterns this task will watch. It can be a string or an array of files and/or minimatch patterns.
tasks
Type: String|Array
This defines which tasks to run when a watched file event occurs.
options.spawn
Type: Boolean
Default: true
Whether to spawn task runs in a child process. Setting this option to false speeds up the reaction time of the watch (usually 500ms faster for most) and allows subsequent task runs to share the same context. Not spawning task runs can make the watch more prone to failing so please use as needed.
For backwards compatibility the option nospawn is still available and will do the opposite of spawn.
options.interrupt
Type: Boolean
Default: false
As files are modified this watch task will spawn tasks in child processes. The default behavior will only spawn a new child process per target when the previous process has finished. Set the interrupt option to true to terminate the previous process and spawn a new one upon later changes.
How long to wait before emitting events in succession for the same filepath and status. For example if your Gruntfile.js file was changed, a changed event will only fire again after the given milliseconds.
The interval is passed to fs.watchFile. Since interval is only used by fs.watchFile and this watcher also uses fs.watch; it is recommended to ignore this option. Default is 100ms.
options.event
Type: String|Array
Default: 'all'
Specify the type of watch events that triggers the specified task. This option can be one or many of: 'all', 'changed', 'added' and 'deleted'.
By default, if Gruntfile.js is being watched, then changes to it will trigger the watch task to restart, and reload the Gruntfile.js changes.
When reload is set to true, changes to any of the watched files will trigger the watch task to restart.
This is especially useful if your Gruntfile.js is dependent on other files.
This is only a task level option and cannot be configured per target. By default the watch task will duck punch grunt.fatal and grunt.warn to try and prevent them from exiting the watch process. If you don't want grunt.fatal and grunt.warn to be overridden set the forever option to false.
options.dateFormat
Type: Function
This is only a task level option and cannot be configured per target. By default when the watch has finished running tasks it will display the message Completed in 1.301s at Thu Jul 18 2013 14:58:21 GMT-0700 (PDT) - Waiting.... You can override this message by supplying your own function:
watch: {options: {dateFormat: function(time){grunt.log.writeln('The watch finished in '+time+'ms at'+(newDate()).toString());grunt.log.writeln('Waiting for more changes...');},},scripts: {files: '**/*.js',tasks: 'jshint',},},
options.atBegin
Type: Boolean
Default: false
This option will trigger the run of each specified task at startup of the watcher.
options.livereload
Type: Boolean|Number|Object
Default: false
Set to true or set livereload: 1337 to a port number to enable live reloading. Default and recommended port is 35729.
If enabled a live reload server will be started with the watch task per target. Then after the indicated tasks have run, the live reload server will be triggered with the modified files.
Passing an object to livereload allows listening on a specific port and hostname/IP or over https connections (by specifying key and cert paths).
Example:
watch: {css: {files: '**/*.sass',tasks: ['sass'],options: {livereload: {host: 'localhost',port: 9000,key: grunt.file.read('path/to/ssl.key'),cert: grunt.file.read('path/to/ssl.crt')// you can pass in any other options you'd like to the https server, as listed here: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener}},},},
options.cwd
Type: String|Object
Default: process.cwd()
Ability to set the current working directory. Defaults to process.cwd(). Can either be a string to set the cwd to match files and spawn tasks or an object to set each independently. Such as:
This will strip off a/path before emitting events. This option is useful for specifying the base directory to use with livereload.
options.livereloadOnError
Type: Boolean
Default: true
Option to prevent the livereload if the executed tasks encountered an error. If set to false, the livereload will only be triggered if all tasks completed successfully.
Examples
// Simple config to run jshint any time a file is added, changed or deletedgrunt.initConfig({watch: {files: ['**/*'],tasks: ['jshint'],},});
// Advanced config. Run specific tasks when specific files are added, changed or deleted.grunt.initConfig({watch: {gruntfile: {files: 'Gruntfile.js',tasks: ['jshint:gruntfile'],},src: {files: ['lib/*.js','css/**/*.scss','!lib/dontwatch.js'],tasks: ['default'],},test: {files: '<%= jshint.test.src %>',tasks: ['jshint:test','qunit'],},},});
Using the watch event
This task will emit a watch event when watched files are modified. This is useful if you would like a simple notification when files are edited or if you're using this task in tandem with another task. Here is a simple example using the watch event:
grunt.initConfig({watch: {scripts: {files: ['lib/*.js'],},},});grunt.event.on('watch',function(action,filepath,target){grunt.log.writeln(target+': '+filepath+' has '+action);});
The watch event is not intended for replacing the standard Grunt API for configuring and running tasks. If you're trying to run tasks from within the watch event you're more than likely doing it wrong. Please read configuring tasks.
Compiling Files As Needed
A very common request is to only compile files as needed. Here is an example that will only lint changed files with the jshint task:
grunt.initConfig({watch: {scripts: {files: ['lib/*.js'],tasks: ['jshint'],options: {spawn: false,},},},jshint: {all: {src: ['lib/*.js'],},},});// On watch events configure jshint:all to only run on changed filegrunt.event.on('watch',function(action,filepath){grunt.config('jshint.all.src',filepath);});
If you need to dynamically modify your config, the spawn option must be disabled to keep the watch running under the same context.
If you save multiple files simultaneously you may opt for a more robust method:
Live reloading is built into the watch task. Set the option livereload to true to enable on the default port 35729 or set to a custom port: livereload: 1337.
The simplest way to add live reloading to all your watch targets is by setting livereload to true at the task level. This will run a single live reload server and trigger the live reload for all your watch targets:
You can also configure live reload for individual watch targets or run multiple live reload servers. Just be sure if you're starting multiple servers they operate on different ports:
grunt.initConfig({watch: {css: {files: ['public/scss/*.scss'],tasks: ['compass'],options: {// Start a live reload server on the default port 35729livereload: true,},},another: {files: ['lib/*.js'],tasks: ['anothertask'],options: {// Start another live reload server on port 1337livereload: 1337,},},dont: {files: ['other/stuff/*'],tasks: ['dostuff'],},},});
Enabling Live Reload in Your HTML
Once you've started a live reload server you'll be able to access the live reload script. To enable live reload on your page, add a script tag before your closing </body> tag pointing to the livereload.js script:
Feel free to add this script to your template situation and toggle with some sort of dev flag.
Using Live Reload with the Browser Extension
Instead of adding a script tag to your page, you can live reload your page by installing a browser extension. Please visit how do I install and use the browser extensions for help installing an extension for your browser.
Once installed please use the default live reload port 35729 and the browser extension will automatically reload your page without needing the <script> tag.
Using Connect Middleware
Since live reloading is used when developing, you may want to disable building for production (and are not using the browser extension). One method is to use Connect middleware to inject the script tag into your page. Try the connect-livereload middleware for injecting the live reload script into your page.
Rolling Your Own Live Reload
Live reloading is made easy by the library tiny-lr. It is encouraged to read the documentation for tiny-lr. If you would like to trigger the live reload server yourself, simply POST files to the URL: http://localhost:35729/changed. Or if you rather roll your own live reload implementation use the following example:
// Create a live reload server instancevarlrserver=require('tiny-lr')();// Listen on port 35729lrserver.listen(35729,function(err){console.log('LR Server Started');});// Then later trigger files or POST to localhost:35729/changedlrserver.changed({body:{files:['public/css/changed.css']}});
Live Reload with Preprocessors
Any time a watched file is edited with the livereload option enabled, the file will be sent to the live reload server. Some edited files you may desire to have sent to the live reload server, such as when preprocessing (sass, less, coffeescript, etc). As any file not recognized will reload the entire page as opposed to just the css or javascript.
The solution is to point a livereload watch target to your destination files:
grunt.initConfig({sass: {dev: {src: ['src/sass/*.sass'],dest: 'dest/css/index.css',},},watch: {sass: {// We watch and compile sass files as normal but don't live reload herefiles: ['src/sass/*.sass'],tasks: ['sass'],},livereload: {// Here we watch the files the sass task will compile to// These files are sent to the live reload server after sass compiles to themoptions: {livereload: true},files: ['dest/**/*'],},},});