-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (45 loc) · 1.63 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
const babel = require("@babel/core");
function changeImportPlugin({ types: t }) {
return {
visitor: {
ImportDeclaration(path, state) {
const options = state.opts;
const memberImports = path.node.specifiers.filter(
(specifier) => specifier.type === "ImportSpecifier",
);
let { node } = path;
const transforms = [];
const source = node.source.value;
const isMatchWithLibrary = source === options.libraryName;
if (isMatchWithLibrary) {
memberImports.forEach((memberImport) => {
const importName = memberImport.imported.name;
const specificImport =
options?.specific?.[importName] ||
options?.specificDestructuring?.[importName];
const replace =
specificImport || `${options.modulePath}/${importName}`;
const destructuringSpecificImport =
options?.specificDestructuring?.[importName];
const newImportSpecifier = destructuringSpecificImport
? t.importSpecifier(
t.identifier(memberImport.local.name),
t.identifier(memberImport.local.name),
)
: t.importDefaultSpecifier(t.identifier(memberImport.local.name));
transforms.push(
t.importDeclaration(
[newImportSpecifier],
t.stringLiteral(replace),
),
);
});
if (transforms.length > 0) {
path.replaceWithMultiple(transforms);
}
}
},
},
};
}
module.exports = changeImportPlugin;