1 | var _ = require('lodash');
|
2 | var async = require('async');
|
3 | var console = require('miaow-util').console;
|
4 | var chokidar = require('chokidar');
|
5 | var minimatch = require('minimatch');
|
6 | var mutil = require('miaow-util');
|
7 | var path = require('path');
|
8 |
|
9 | function Watcher(compiler) {
|
10 | this.compiler = compiler;
|
11 | }
|
12 |
|
13 | Watcher.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 |
|
23 | Watcher.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 |
|
57 | module.exports = Watcher;
|