source: Dev/trunk/node_modules/grunt-contrib-watch/README.md @ 533

Last change on this file since 533 was 533, checked in by hendrikvanantwerpen, 10 years ago

Add watch command to ease client development.

File size: 20.0 KB
RevLine 
[533]1# grunt-contrib-watch v0.6.1 [![Build Status](https://travis-ci.org/gruntjs/grunt-contrib-watch.png?branch=master)](https://travis-ci.org/gruntjs/grunt-contrib-watch)
2
3> Run predefined tasks whenever watched file patterns are added, changed or deleted.
4
5
6
7## Getting Started
8This plugin requires Grunt `~0.4.0`
9
10If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
11
12```shell
13npm install grunt-contrib-watch --save-dev
14```
15
16Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
17
18```js
19grunt.loadNpmTasks('grunt-contrib-watch');
20```
21
22
23
24
25## Watch task
26_Run this task with the `grunt watch` command._
27
28
29### Settings
30
31There are a number of options available. Please review the [minimatch options here](https://github.com/isaacs/minimatch#options). As well as some additional options as follows:
32
33#### files
34Type: `String|Array`
35
36This defines what file patterns this task will watch. Can be a string or an array of files and/or minimatch patterns.
37
38#### tasks
39Type: `String|Array`
40
41This defines which tasks to run when a watched file event occurs.
42
43#### options.spawn
44Type: `Boolean`
45Default: true
46
47Whether 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.
48
49Example:
50```js
51watch: {
52  scripts: {
53    files: ['**/*.js'],
54    tasks: ['jshint'],
55    options: {
56      spawn: false,
57    },
58  },
59},
60```
61
62*For backwards compatibility the option `nospawn` is still available and will do the opposite of `spawn`.*
63
64#### options.interrupt
65Type: `Boolean`
66Default: false
67
68As 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.
69
70Example:
71```js
72watch: {
73  scripts: {
74    files: '**/*.js',
75    tasks: ['jshint'],
76    options: {
77      interrupt: true,
78    },
79  },
80},
81```
82
83#### options.debounceDelay
84Type: `Integer`
85Default: 500
86
87How 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.
88
89Example:
90```js
91watch: {
92  scripts: {
93    files: '**/*.js',
94    tasks: ['jshint'],
95    options: {
96      debounceDelay: 250,
97    },
98  },
99},
100```
101
102#### options.interval
103Type: `Integer`
104Default: 100
105
106The `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*.
107
108#### options.event
109Type: `String|Array`
110Default: `'all'`
111
112Specify the type watch event that trigger the specified task. This option can be one or many of: `'all'`, `'changed'`, `'added'` and `'deleted'`.
113
114Example:
115```js
116watch: {
117  scripts: {
118    files: '**/*.js',
119    tasks: ['generateFileManifest'],
120    options: {
121      event: ['added', 'deleted'],
122    },
123  },
124},
125```
126
127#### options.reload
128Type: `Boolean`
129Default: `false`
130
131By default, if `Gruntfile.js` is being watched, then changes to it will trigger the watch task to restart, and reload the `Gruntfile.js` changes.
132When `reload` is set to `true`, changes to *any* of the watched files will trigger the watch task to restart.
133This is especially useful if your `Gruntfile.js` is dependent on other files.
134
135```js
136watch: {
137  configFiles: {
138    files: [ 'Gruntfile.js', 'config/*.js' ],
139    options: {
140      reload: true
141    }
142  }
143}
144```
145
146
147#### options.forever
148Type: `Boolean`
149Default: true
150
151This 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`.
152
153#### options.dateFormat
154Type: `Function`
155
156This 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:
157
158```js
159watch: {
160  options: {
161    dateFormat: function(time) {
162      grunt.log.writeln('The watch finished in ' + time + 'ms at' + (new Date()).toString());
163      grunt.log.writeln('Waiting for more changes...');
164    },
165  },
166  scripts: {
167    files: '**/*.js',
168    tasks: 'jshint',
169  },
170},
171```
172
173#### options.atBegin
174Type: `Boolean`
175Default: false
176
177This option will trigger the run of each specified task at startup of the watcher.
178
179#### options.livereload
180Type: `Boolean|Number|Object`
181Default: false
182
183Set to `true` or set `livereload: 1337` to a port number to enable live reloading. Default and recommended port is `35729`.
184
185If enabled a live reload server will be started with the watch task per target. Then after the indicated tasks have ran, the live reload server will be triggered with the modified files.
186
187Example:
188```js
189watch: {
190  css: {
191    files: '**/*.sass',
192    tasks: ['sass'],
193    options: {
194      livereload: true,
195    },
196  },
197},
198```
199
200It's possible to get livereload working over https connections. To do this, pass an object to `livereload` with a `key` and `cert` paths specified.
201
202Example:
203```js
204watch: {
205  css: {
206    files: '**/*.sass',
207    tasks: ['sass'],
208    options: {
209      livereload: {
210        port: 9000,
211        key: grunt.file.read('path/to/ssl.key'),
212        cert: grunt.file.read('path/to/ssl.crt')
213        // 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
214      }
215    },
216  },
217},
218```
219
220
221#### options.cwd
222Type: `String|Object`
223Default: `process.cwd()`
224
225Ability 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 `options: { cwd: { files: 'match/files/from/here', spawn: 'but/spawn/files/from/here' } }`.
226
227#### options.livereloadOnError
228Type: `Boolean` 
229Default: `true` 
230
231Option 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.
232
233### Examples
234
235```js
236// Simple config to run jshint any time a file is added, changed or deleted
237grunt.initConfig({
238  watch: {
239    files: ['**/*'],
240    tasks: ['jshint'],
241  },
242});
243```
244
245```js
246// Advanced config. Run specific tasks when specific files are added, changed or deleted.
247grunt.initConfig({
248  watch: {
249    gruntfile: {
250      files: 'Gruntfile.js',
251      tasks: ['jshint:gruntfile'],
252    },
253    src: {
254      files: ['lib/*.js', 'css/**/*.scss', '!lib/dontwatch.js'],
255      tasks: ['default'],
256    },
257    test: {
258      files: '<%= jshint.test.src %>',
259      tasks: ['jshint:test', 'qunit'],
260    },
261  },
262});
263```
264
265#### Using the `watch` event
266This 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:
267
268```js
269grunt.initConfig({
270  watch: {
271    scripts: {
272      files: ['lib/*.js'],
273    },
274  },
275});
276grunt.event.on('watch', function(action, filepath, target) {
277  grunt.log.writeln(target + ': ' + filepath + ' has ' + action);
278});
279```
280
281**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](http://gruntjs.com/configuring-tasks).**
282
283##### Compiling Files As Needed
284A very common request is to only compile files as needed. Here is an example that will only lint changed files with the `jshint` task:
285
286```js
287grunt.initConfig({
288  watch: {
289    scripts: {
290      files: ['lib/*.js'],
291      tasks: ['jshint'],
292      options: {
293        spawn: false,
294      },
295    },
296  },
297  jshint: {
298    all: {
299      src: ['lib/*.js'],
300    },
301  },
302});
303
304// on watch events configure jshint:all to only run on changed file
305grunt.event.on('watch', function(action, filepath) {
306  grunt.config('jshint.all.src', filepath);
307});
308```
309
310If you need to dynamically modify your config, the `spawn` option must be disabled to keep the watch running under the same context.
311
312If you save multiple files simultaneously you may opt for a more robust method:
313
314```js
315var changedFiles = Object.create(null);
316var onChange = grunt.util._.debounce(function() {
317  grunt.config('jshint.all.src', Object.keys(changedFiles));
318  changedFiles = Object.create(null);
319}, 200);
320grunt.event.on('watch', function(action, filepath) {
321  changedFiles[filepath] = action;
322  onChange();
323});
324```
325
326#### Live Reloading
327Live 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`.
328
329The 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:
330
331```js
332grunt.initConfig({
333  watch: {
334    options: {
335      livereload: true,
336    },
337    css: {
338      files: ['public/scss/*.scss'],
339      tasks: ['compass'],
340    },
341  },
342});
343```
344
345You 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:
346
347```js
348grunt.initConfig({
349  watch: {
350    css: {
351      files: ['public/scss/*.scss'],
352      tasks: ['compass'],
353      options: {
354        // Start a live reload server on the default port 35729
355        livereload: true,
356      },
357    },
358    another: {
359      files: ['lib/*.js'],
360      tasks: ['anothertask'],
361      options: {
362        // Start another live reload server on port 1337
363        livereload: 1337,
364      },
365    },
366    dont: {
367      files: ['other/stuff/*'],
368      tasks: ['dostuff'],
369    },
370  },
371});
372```
373
374##### Enabling Live Reload in Your HTML
375Once 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:
376
377```html
378<script src="//localhost:35729/livereload.js"></script>
379```
380
381Feel free to add this script to your template situation and toggle with some sort of `dev` flag.
382
383##### Using Live Reload with the Browser Extension
384Instead 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](http://feedback.livereload.com/knowledgebase/articles/86242-how-do-i-install-and-use-the-browser-extensions-) for help installing an extension for your browser.
385
386Once installed please use the default live reload port `35729` and the browser extension will automatically reload your page without needing the `<script>` tag.
387
388##### Using Connect Middleware
389Since 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](https://github.com/intesso/connect-livereload) middleware for injecting the live reload script into your page.
390
391##### Rolling Your Own Live Reload
392Live reloading is made easy by the library [tiny-lr](https://github.com/mklabs/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:
393
394```js
395// Create a live reload server instance
396var lrserver = require('tiny-lr')();
397
398// Listen on port 35729
399lrserver.listen(35729, function(err) { console.log('LR Server Started'); });
400
401// Then later trigger files or POST to localhost:35729/changed
402lrserver.changed({body:{files:['public/css/changed.css']}});
403```
404
405##### Live Reload with Preprocessors
406Any 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`.
407
408The solution is to point a `livereload` watch target to your destination files:
409
410```js
411grunt.initConfig({
412  sass: {
413    dev: {
414      src: ['src/sass/*.sass'],
415      dest: 'dest/css/index.css',
416    },
417  },
418  watch: {
419    sass: {
420      // We watch and compile sass files as normal but don't live reload here
421      files: ['src/sass/*.sass'],
422      tasks: ['sass'],
423    },
424    livereload: {
425      // Here we watch the files the sass task will compile to
426      // These files are sent to the live reload server after sass compiles to them
427      options: { livereload: true },
428      files: ['dest/**/*'],
429    },
430  },
431});
432```
433
434### FAQs
435
436#### How do I fix the error `EMFILE: Too many opened files.`?
437This is because of your system's max opened file limit. For OSX the default is very low (256). Temporarily increase your limit with `ulimit -n 10480`, the number being the new max limit.
438
439In some versions of OSX the above solution doesn't work. In that case try `launchctl limit maxfiles 10480 10480 ` and restart your terminal. See [here](http://superuser.com/questions/261023/how-to-change-default-ulimit-values-in-mac-os-x-10-6).
440
441#### Can I use this with Grunt v0.3?
442`grunt-contrib-watch@0.1.x` is compatible with Grunt v0.3 but it is highly recommended to upgrade Grunt instead.
443
444#### Why is the watch devouring all my memory/cpu?
445Likely because of an enthusiastic pattern trying to watch thousands of files. Such as `'**/*.js'` but forgetting to exclude the `node_modules` folder with `'!**/node_modules/**'`. Try grouping your files within a subfolder or be more explicit with your file matching pattern.
446
447Another reason if you're watching a large number of files could be the low default `interval`. Try increasing with `options: { interval: 5007 }`. Please see issues [#35](https://github.com/gruntjs/grunt-contrib-watch/issues/145) and [#145](https://github.com/gruntjs/grunt-contrib-watch/issues/145) for more information.
448
449#### Why spawn as child processes as a default?
450The goal of this watch task is as files are changed, run tasks as if they were triggered by the user themself. Each time a user runs `grunt` a process is spawned and tasks are ran in succession. In an effort to keep the experience consistent and continually produce expected results, this watch task spawns tasks as child processes by default.
451
452Sandboxing task runs also allows this watch task to run more stable over long periods of time. As well as more efficiently with more complex tasks and file structures.
453
454Spawning does cause a performance hit (usually 500ms for most environments). It also cripples tasks that rely on the watch task to share the context with each subsequent run (i.e., reload tasks). If you would like a faster watch task or need to share the context please set the `spawn` option to `false`. Just be aware that with this option enabled, the watch task is more prone to failure.
455
456
457## Release History
458
459 * 2014-03-19   v0.6.1   Fix for watch targets named "default"
460 * 2014-03-11   v0.6.0   Clear changed files after triggering live reload to ensure they're only triggered once. cwd option now accepts separate settings for files and spawn. Fix to make interrupt work more than once. Enable live reload over HTTPS. Print newline after initial 'Waiting...' Remove deprecated grunt.util libs Add reload option to specify files other than Gruntfile files to reload. Update to gaze@0.5.1 Use fork of tiny-lr (which has quiter operation, support for HTTPS and windows path fixes) Add livereloadOnError, which if set to false will not trigger live reload if there is an error.
461 * 2013-08-25   v0.5.3   Fixed for live reload missing files.
462 * 2013-08-16   v0.5.2   Fixed issue running tasks after gruntfile is reloaded. Ignores empty file paths.
463 * 2013-07-20   v0.5.1   Fixed issue with options resetting.
464 * 2013-07-18   v0.5.0   Added target name to watch event. Added atBegin option to run tasks when watcher starts. Changed nospawn option to spawn (nospawn still available for backwards compatibility). Moved libs/vars into top scope to prevent re-init. Bumped Gaze version to ~0.4. Re-grab task/target options upon each task run. Add dateFormat option to override the date/time output upon completion.
465 * 2013-05-27   v0.4.4   Remove gracefully closing SIGINT. Not needed and causes problems for Windows. Ensure tasks are an array to not conflict with cliArgs.
466 * 2013-05-11   v0.4.3   Only group changed files per target to send correct files to live reload.
467 * 2013-05-09   v0.4.2   Fix for closing watchers.
468 * 2013-05-09   v0.4.1   Removed "beep" notification. Tasks now optional with livereload option. Reverted "run again" with interrupt off to fix infinite recursion issue. Watchers now close more properly on task run.
469 * 2013-05-03   v0.4.0   Option livereload to start live reload servers. Will reload a Gruntfile before running tasks if Gruntfile is modified. Option event to only trigger watch on certain events. Refactor watch task into separate task runs per target. Option forever to override grunt.fatal/warn to help keeping the watch alive with nospawn enabled. Emit a beep upon complete. Logs all watched files with verbose flag set. If interrupt is off, will run the tasks once more if watch triggered during a previous task run. tasks property is optional for use with watch event. Watchers properly closed when exiting.
470 * 2013-02-28   v0.3.1   Fix for top level options.
471 * 2013-02-27   v0.3.0   nospawn option added to run tasks without spawning as child processes. Watch emits 'watch' events upon files being triggered with grunt.event. Completion time in seconds and date/time shown after tasks ran. Negate file patterns fixed. Tasks debounced individually to handle simultaneous triggering for multiple targets. Errors handled better and viewable with --stack cli option. Code complexity reduced making the watch task code easier to read.
472 * 2013-02-15   v0.2.0   First official release for Grunt 0.4.0.
473 * 2013-01-18   v0.2.0rc7   Updating grunt/gruntplugin dependencies to rc6. Changing in-development grunt/gruntplugin dependency versions from tilde version ranges to specific versions.
474 * 2013-01-09   v0.2.0rc5   Updating to work with grunt v0.4.0rc5.
475 * 2012-12-15   v0.2.0a   Conversion to grunt v0.4 conventions. Remove node v0.6 and grunt v0.3 support. Allow watch task to be renamed. Use grunt.util.spawn "grunt" option. Updated to gaze@0.3.0, forceWatchMethod option removed.
476 * 2012-11-01   v0.1.4   Prevent watch from spawning duplicate watch tasks
477 * 2012-10-28   v0.1.3   Better method to spawn the grunt bin Bump gaze to v0.2.0. Better handles some events and new option forceWatchMethod Only support Node.js >= v0.8
478 * 2012-10-17   v0.1.2   Only spawn a process per task one at a time Add interrupt option to cancel previous spawned process Grunt v0.3 compatibility changes
479 * 2012-10-16   v0.1.1   Fallback to global grunt bin if local doesnt exist. Fatal if bin cannot be found Update to gaze 0.1.6
480 * 2012-10-08   v0.1.0   Release watch task Remove spawn from helper Run on Grunt v0.4
481
482---
483
484Task submitted by [Kyle Robinson Young](http://dontkry.com)
485
486*This file was generated on Wed Mar 19 2014 13:09:11.*
Note: See TracBrowser for help on using the repository browser.