forked from JonasDoebertin/webpack-watch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (42 loc) · 1.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const chokidar = require('chokidar');
const debounce = require('lodash.debounce');
const fs = require('fs');
class WatchPlugin {
constructor(config) {
this.config = config;
this.firstPassDone = false;
}
apply(compiler) {
this.compiler = compiler;
compiler.plugin('watch-run', (params, callback) => {
if (!this.watcher) {
this.startWatcher();
}
callback();
});
compiler.plugin('done', () => {
this.firstPassDone = true;
})
}
startWatcher() {
this.watcher = chokidar.watch(this.config.paths, this.config.options);
const run = debounce(this.runCompiler.bind(this), 500);
this.watcher.on('add', (path) => { run() });
this.watcher.on('change', (path) => { run() });
this.watcher.on('unlink', (path) => { run() });
}
stopWatcher() {
this.watcher.close();
}
runCompiler() {
if (this.firstPassDone) {
this.compiler.run(error => {
if (error) {
this.stopWatcher();
throw error;
}
});
}
}
}
module.exports = WatchPlugin;