forked from kentor/invalidate-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
34 lines (28 loc) · 970 Bytes
/
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
const Module = require('module');
const DepGraph = require('dependency-graph').DepGraph;
const graph = new DepGraph();
const __require = Module.prototype.require;
Module.prototype.require = function(path) {
const requiredModule = __require.call(this, path);
const requiredModuleFilename = Module._resolveFilename(path, this);
graph.addNode(this.filename);
graph.addNode(requiredModuleFilename);
graph.addDependency(this.filename, requiredModuleFilename);
return requiredModule;
};
function invalidate(absPathToModule) {
if (graph.hasNode(absPathToModule)) {
graph.dependantsOf(absPathToModule).concat([absPathToModule]).forEach(m => {
const mod = require.cache[m];
if (mod) {
const siblings = mod.parent.children.indexOf(mod);
if (siblings >= 0) {
mod.parent.children.splice(siblings, 1);
}
}
delete require.cache[m];
graph.removeNode(m);
});
}
}
module.exports = invalidate;