-
Notifications
You must be signed in to change notification settings - Fork 0
/
hmr.js
102 lines (85 loc) · 2.34 KB
/
hmr.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* eslint-disable import/no-dynamic-require */
/* eslint-disable global-require */
/* eslint-disable no-console */
const watchGlob = require('watch-glob');
const { throttle } = require('lodash');
export default class HmrBase {
constructor(script, config) {
this.script = script;
this.server = null;
this.module = null;
this.startThrottled = throttle(() => {
console.time(`[HMR] - ${script.name}`);
this.start(() => {
console.timeEnd(`[HMR] - ${script.name}`);
});
}, config.throttling);
}
require(relativePath) {
const { root } = this.script;
return require(`${root || process.cwd()}/${relativePath}`).default;
}
clearModuleCache() {
const { keepCache } = this.script;
Object.keys(require.cache).forEach((key) => {
const keepCached = keepCache && keepCache.find(cache => key.includes(cache));
if (!key.includes('node_modules') && !keepCached) {
delete require.cache[key];
}
});
}
launch() {
const { name, watch, spawn } = this.script;
console.time(`[Launching] - ${name}`);
return new Promise((resolve) => {
watchGlob(watch, { callbackArg: 'relative' }, (path) => {
console.log(`[File Changed] - ${path}`);
if (spawn) {
process.exit();
}
this.clearModuleCache();
this.startThrottled();
});
this.start(() => {
console.timeEnd(`[Launching] - ${name}`);
resolve();
});
});
}
}
export class ModuleHmr extends HmrBase {
start(done) {
const { path } = this.script;
this.module = this.require(path);
done();
}
}
export class QueueHmr extends HmrBase {
start(done) {
const { options: { queuePath }, path } = this.script;
const queue = this.require(queuePath);
if (!queue.workers.length) {
this.module = this.require(path);
this.module();
return done();
}
return queue.shutdown(0, () => {
this.clearModuleCache();
this.module = this.require(path);
this.module();
return done();
});
}
}
export class ExpressHmr extends HmrBase {
start(done) {
const { path } = this.script;
this.module = this.require(path);
if (this.server) {
this.server.close();
this.server = null;
}
this.server = this.module.listen(process.env.PORT)
.on('listening', done);
}
}