-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
65 lines (60 loc) · 2.01 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
/* eslint-disable no-param-reassign */
function isModule(value, original) {
const pattern = new RegExp(`^(${original}|${original}/.*)$`);
return pattern.test(value);
}
function replace(value, original, replacement) {
const pattern = new RegExp(`^${original}`);
return value.replace(pattern, replacement);
}
function getReplacements(state) {
if (state.opts instanceof Array) {
return state.opts;
} else if (state.opts && state.opts.replacements instanceof Array) {
return state.opts.replacements;
}
return [state.opts];
}
export default function visitor({ types: t }) {
const source = (value, original, replacement) =>
t.stringLiteral(replace(value, original, replacement));
return {
visitor: {
ImportDeclaration(path, state) {
const replacements = getReplacements(state);
replacements.forEach(({ original, replacement }) => {
const { value } = path.node.source;
if (isModule(value, original)) {
path.node.source = source(value, original, replacement);
}
});
},
ExportDeclaration(path, state) {
const replacements = getReplacements(state);
replacements.forEach(({ original, replacement }) => {
const { node } = path;
if (node.source && isModule(node.source.value, original)) {
path.node.source = source(node.source.value, original, replacement);
}
});
},
CallExpression(path, state) {
const replacements = getReplacements(state);
replacements.forEach(({ original, replacement }) => {
const { node } = path;
if (
node.callee.name === "require" &&
node.arguments &&
node.arguments.length === 1 &&
t.isStringLiteral(node.arguments[0]) &&
isModule(node.arguments[0].value, original)
) {
path.node.arguments = [
source(node.arguments[0].value, original, replacement)
];
}
});
}
}
};
}