UNPKG

1.81 kBJavaScriptView Raw
1var tinylr = require('tiny-lr');
2var Gaze = require('gaze').Gaze;
3var log = require('./log');
4
5var CSS_EXTENSIONS = ['.css', '.styl', '.scss', '.sass', '.less'];
6
7module.exports = function(options, callback) {
8 // Defaulting to poll mode as native was observed to fail silently even
9 // though it is supposed to automatically fallback to polling. Allow
10 // this to be overridden in package.json in the _aerobatic section.
11 var gazeOptions = {
12 maxListeners: 100,
13 mode: 'poll', // program.watchMode === 'auto' ? 'auto' : 'poll',
14 cwd: options.baseDir
15 };
16
17 var liveReloadOptions = {
18 liveCSS: true, liveImg: true
19 };
20
21 if (options.https)
22 _.extend(liveReloadOptions, options.https);
23
24 var liveReloadServer = tinylr(liveReloadOptions);
25
26 // Make sure to call listen on a new line rather than chain it to the factory function
27 // since the listen function does not return the server reference.
28 liveReloadServer.listen(options.liveReloadPort, function() {
29 log.info("LiveReload listening on port %s", options.liveReloadPort);
30
31 liveReloadServer.on('close', function() {
32 watcher.close();
33 });
34
35 new Gaze("**/*", gazeOptions, function(err, watcher) {
36 if (err) return callback(err);
37
38 this.on('all', function(filePath) {
39 log.info("LiveReload triggered by change to %s", filePath);
40
41 // if this is a css file or something that compiles to css,
42 // try and just refresh the css without a full page reload.
43 var ext = path.extname(filePath);
44 if (_.contains(CSS_EXTENSIONS, ext))
45 tinylr.changed('*.css');
46 else
47 tinylr.changed();
48 });
49
50 this.on('error', function(err) {
51 log.warn("Watch error %s", err.message);
52 });
53
54 callback(null, liveReloadServer);
55 });
56 });
57};