-
Notifications
You must be signed in to change notification settings - Fork 66
/
utils.js
52 lines (42 loc) · 1.56 KB
/
utils.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
export function getImportSource(t, callNode) {
const importArguments = callNode.arguments;
const [importPath] = importArguments;
const isString = t.isStringLiteral(importPath) || t.isTemplateLiteral(importPath);
if (isString) {
t.removeComments(importPath);
return importPath;
}
return t.templateLiteral([
t.templateElement({ raw: '', cooked: '' }),
t.templateElement({ raw: '', cooked: '' }, true),
], importArguments);
}
export function createDynamicImportTransform({ template, types: t }) {
const builders = {
static: {
interop: template('Promise.resolve().then(() => INTEROP(require(SOURCE)))'),
noInterop: template('Promise.resolve().then(() => require(SOURCE))'),
},
dynamic: {
interop: template('Promise.resolve(SOURCE).then(s => INTEROP(require(s)))'),
noInterop: template('Promise.resolve(SOURCE).then(s => require(s))'),
},
};
const visited = typeof WeakSet === 'function' && new WeakSet();
const isString = (node) => t.isStringLiteral(node)
|| (t.isTemplateLiteral(node) && node.expressions.length === 0);
return (context, path) => {
if (visited) {
if (visited.has(path)) {
return;
}
visited.add(path);
}
const SOURCE = getImportSource(t, path.parent);
const builder = isString(SOURCE) ? builders.static : builders.dynamic;
const newImport = context.opts.noInterop
? builder.noInterop({ SOURCE })
: builder.interop({ SOURCE, INTEROP: context.addHelper('interopRequireWildcard') });
path.parentPath.replaceWith(newImport);
};
}