-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (56 loc) · 1.7 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const fs = require('fs');
const mod = require('module');
const path = require('path');
const requirearchy = [];
const requireParents = {};
const watching = {};
function requireWithHotReload(id) {
let modulePath = mod._resolveFilename(id, this, false);
requirearchy.push(modulePath);
let ret = mod.prototype._require.call(this, id);
requirearchy.pop();
if (ret && fs.existsSync(modulePath)) {
requireParents[modulePath] = requireParents[modulePath] || {};
if (!watching[modulePath]) {
watching[modulePath] = fs.watch(modulePath, {
persistent: false,
}, function () {
let resetList = [modulePath];
if (requireParents[modulePath]) {
for (let key in requireParents[modulePath]) {
if (requireParents[modulePath][key]) {
resetList.push(key);
}
}
}
resetList.forEach(key => {
if (require.cache[key]) {
delete require.cache[key];
}
if (watching[key]) {
watching[key].close();
watching[key] = false;
}
});
});
}
requirearchy.forEach(parent => {
if (fs.existsSync(parent)) {
requireParents[modulePath][parent] = true;
}
});
}
return ret;
}
function initHotReload () {
if (!mod.prototype._require && mod.prototype.require !== requireWithHotReload) {
mod.prototype._require = mod.prototype.require;
mod.prototype.require = requireWithHotReload;
} else {
throw new Error('Unable to init require with hot reload!');
}
}
module.exports = initHotReload;
module.exports.init = initHotReload;
module.exports.requireParents = requireParents;
module.exports.watching = watching;