forked from sindresorhus/clear-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (81 loc) · 2.47 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
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
103
'use strict';
const path = require('path');
const resolveFrom = require('resolve-from').silent;
const parentModule = require('parent-module');
const resolve = (moduleId, options = {}) => {
const basePath = options.basePath || path.dirname(parentModule(__filename));
try {
return resolveFrom(basePath, moduleId);
} catch (_) {}
};
const clear = (moduleId, options = {}) => {
const { regex, isExclusiveFilter = false } = options;
if (typeof moduleId !== 'string') {
throw new TypeError(`Expected a \`string\`, got \`${typeof moduleId}\``);
}
const filePath = resolve(moduleId, options);
if (!filePath) {
return
}
if (regex) {
const moduleMatches = regex.test(filePath);
const shouldSkipModule = isExclusiveFilter ? moduleMatches : !moduleMatches;
if (shouldSkipModule) {
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]) {
let children = require.cache[filePath].children.map(child => child.id);
// Filter out children not matching regex (if provided)
if (regex) {
children = children.filter(moduleId => {
const modulePath = resolve(moduleId, options);
const moduleMatches = regex.test(modulePath);
return isExclusiveFilter ? !moduleMatches : moduleMatches;
});
}
// Delete module from cache
delete require.cache[filePath];
for (const id of children) {
clear(id, options);
}
}
};
clear.all = (options = {}) => {
const { regex, isExclusiveFilter = false } = options;
const directory = path.dirname(parentModule(__filename));
for (const moduleId of Object.keys(require.cache)) {
if (regex) {
const moduleMatches = regex.test(moduleId);
const shouldSkipModule = isExclusiveFilter ? moduleMatches : !moduleMatches;
if (shouldSkipModule) {
continue;
}
}
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;