UNPKG

1.53 kBJavaScriptView Raw
1var _ = require('lodash');
2var async = require('async');
3var console = require('miaow-util').console;
4var chokidar = require('chokidar');
5var minimatch = require('minimatch');
6var mutil = require('miaow-util');
7var path = require('path');
8
9function Watcher(compiler) {
10 this.compiler = compiler;
11}
12
13Watcher.prototype.watch = function(callback) {
14 this.compiler.applyPluginsAsync('watch', function(err) {
15 if (err) {
16 return callback(err);
17 }
18
19 this.start(callback);
20 }.bind(this));
21};
22
23Watcher.prototype.start = function(outcallback) {
24 var compiler = this.compiler;
25 var queue = async.queue(function(task, callback) {
26 compiler.compile(function(err) {
27 outcallback(err);
28 callback();
29 });
30 }, 1);
31
32 queue.push('', function() {
33 var exclude = compiler.options.exclude.concat(['**/.*', '**/.*/**/*']);
34 var watcher = chokidar.watch(compiler.context, {
35 cwd: compiler.context,
36 ignored: [function(file) {
37 var relativePath = mutil.relative(compiler.context, file);
38 var basename = path.basename(file);
39 var match = _.partial(minimatch, relativePath, _, {matchBase: true, dot: true});
40
41 return basename !== 'package.json' && (basename === 'miaow.config.js' || !!_.find(exclude, match));
42 }]
43 });
44
45 watcher.on('ready', function() {
46 console.log('开始监听');
47
48 watcher.on('all', function() {
49 if (queue.length() === 0) {
50 queue.push('', _.noop);
51 }
52 });
53 });
54 });
55};
56
57module.exports = Watcher;