UNPKG

1.81 kBJavaScriptView Raw
1const SKIP = Symbol('SKIP');
2
3module.exports = function rewire(babel, options) {
4 const t = babel.types;
5
6 const { name, index, mappings } = require(options.mappings ||
7 '../../mappings.json');
8
9 return {
10 visitor: {
11 ImportDeclaration(path) {
12 if (path.node.source.value !== name || path.node[SKIP]) {
13 return;
14 }
15
16 path.node.source.value = `${name}/${index}`;
17 path.replaceWithMultiple(
18 path.node.specifiers.reduce((declarations, specifier) => {
19 const mapping = mappings[specifier.imported.name];
20
21 if (mapping) {
22 const alias = `${name}/${mapping.path}`;
23 const identifier = t.identifier(specifier.local.name);
24
25 let s;
26
27 switch (mapping.name) {
28 case 'default':
29 s = t.importDefaultSpecifier(identifier);
30 break;
31 case '*':
32 s = t.importNamespaceSpecifier(identifier);
33 break;
34 default:
35 s = t.importSpecifier(identifier, t.identifier(mapping.name));
36 }
37
38 declarations.push(
39 t.importDeclaration([s], t.stringLiteral(alias))
40 );
41 } else {
42 const previous = declarations.find(
43 (d) => d.source.value === path.node.source.value
44 );
45
46 if (previous) {
47 previous.specifiers.push(specifier);
48 } else {
49 const node = t.importDeclaration([specifier], path.node.source);
50 node[SKIP] = true;
51 declarations.push(node);
52 }
53 }
54
55 return declarations;
56 }, [])
57 );
58
59 path.requeue();
60 },
61 },
62 };
63};