-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathindex.js
71 lines (56 loc) · 1.59 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
70
71
'use strict';
const path = require('path');
const resolveFrom = require('resolve-from');
const parentModule = require('parent-module');
const resolve = moduleId => {
try {
return resolveFrom(path.dirname(parentModule(__filename)), moduleId);
} catch (_) {}
};
const clear = moduleId => {
if (typeof moduleId !== 'string') {
throw new TypeError(`Expected a \`string\`, got \`${typeof moduleId}\``);
}
const filePath = resolve(moduleId);
if (!filePath) {
return;
}
// Delete itself from module parent
if (require.cache[filePath] && require.cache[filePath].parent) {
let i = require.cache[filePath].parent.children.length;
while (i--) {
if (require.cache[filePath].parent.children[i].id === filePath) {
require.cache[filePath].parent.children.splice(i, 1);
}
}
}
// Remove all descendants from cache as well
if (require.cache[filePath]) {
const children = require.cache[filePath].children.map(child => child.id);
// Delete module from cache
delete require.cache[filePath];
for (const id of children) {
clear(id);
}
}
};
clear.all = () => {
const directory = path.dirname(parentModule(__filename));
for (const moduleId of Object.keys(require.cache)) {
delete require.cache[resolveFrom(directory, moduleId)];
}
};
clear.match = regex => {
for (const moduleId of Object.keys(require.cache)) {
if (regex.test(moduleId)) {
clear(moduleId);
}
}
};
clear.single = moduleId => {
if (typeof moduleId !== 'string') {
throw new TypeError(`Expected a \`string\`, got \`${typeof moduleId}\``);
}
delete require.cache[resolve(moduleId)];
};
module.exports = clear;