-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
101 lines (80 loc) · 2.36 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// @flow
'use strict';
const explodeModule = require('babel-explode-module');
const t = require('babel-types');
/*::
type Node = {
type: string,
[key: string]: any,
};
type Path = {
type: string,
node: Node,
[key: string]: any,
};
*/
function toModuleSpecifierValues(specifier) {
return {
local: specifier.local ? t.identifier(specifier.local) : null,
external: specifier.external ? t.identifier(specifier.external) : null,
source: specifier.source ? t.stringLiteral(specifier.source) : null,
};
}
function explodedToStatements(exploded /*: Object */) {
let statements = [];
exploded.imports.forEach(item => {
let {local, external, source} = toModuleSpecifierValues(item);
let specifier;
// If import is for side effects, it has no specifiers.
if (!external && !local) {
return;
}
if (!external) {
specifier = t.importNamespaceSpecifier(local);
} else if (item.external === 'default') {
specifier = t.importDefaultSpecifier(local);
} else {
specifier = t.importSpecifier(local, external);
}
let declaration = t.importDeclaration([specifier], source);
declaration.importKind = item.kind;
declaration.loc = specifier.loc = item.loc;
statements.push(declaration);
});
exploded.statements.forEach(item => {
statements.push(item);
});
exploded.exports.forEach(item => {
let {local, external, source} = toModuleSpecifierValues(item);
let declaration;
if (!source && item.external === 'default') {
declaration = t.exportDefaultDeclaration(local);
} else if (source && !local && !external) {
declaration = t.exportAllDeclaration(source);
} else {
let specifier = t.exportSpecifier(local, external);
specifier.loc = item.loc;
declaration = t.exportNamedDeclaration(null, [specifier], source);
}
declaration.loc = item.loc;
statements.push(declaration);
});
return statements;
}
function simplifyModule(path /*: Path */) {
if (!path.isProgram()) {
throw new Error(
`Must call simplifyModule() with Program node, passed: ${path.type}`
);
}
let exploded = explodeModule(path.node);
let statements = explodedToStatements(exploded);
let program = Object.assign({}, path.node, {
body: statements,
});
path.replaceWith(program);
}
module.exports = {
explodedToStatements,
simplifyModule,
};