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