-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
67 lines (57 loc) · 1.72 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
/* @flow */
const dirname = require('path').dirname;
const resolve = require('resolve-from');
const isBuiltin = require('is-builtin-module');
module.exports = function rewire(babel /*: any */) {
const t = babel.types;
return {
visitor: {
TryStatement(path /*: any */, state /*: any */) {
path.get('block').traverse({
CallExpression(p) {
if (
p.node.callee.name !== 'require' ||
p.node.arguments.length !== 1
) {
return;
}
const {
builtins = false,
blacklist = [],
whitelist = [],
} = state.opts;
const name = p.get('arguments')[0].evaluate().value;
if (typeof name !== 'string') {
return;
}
if (whitelist.includes(name)) {
return;
}
const cwd =
state.file && state.file.opts && state.file.opts.filename
? dirname(state.file.opts.filename)
: process.cwd();
try {
if (blacklist.includes(name)) {
throw new Error(`Cannot find module '${name}'`);
}
if (builtins !== true && isBuiltin(name)) {
throw new Error(`Cannot resolve builtin module '${name}'`);
} else {
resolve(cwd, name);
}
} catch (e) {
p.replaceWith(
t.throwStatement(
t.newExpression(t.identifier('Error'), [
t.stringLiteral(e.message),
])
)
);
}
},
});
},
},
};
};