-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathremoveUnusedImports.js
96 lines (86 loc) · 2.87 KB
/
removeUnusedImports.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
export default function transformer(file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
const removeIfUnused = (importSpecifier, importDeclaration) => {
const varName = importSpecifier.value.local.name;
if (varName === "React") {
return false;
}
const isUsedInScopes = () => {
return (
j(importDeclaration)
.closestScope()
.find(j.Identifier, { name: varName })
.filter((p) => {
if (p.value.start === importSpecifier.value.local.start)
return false;
if (p.parentPath.value.type === "Property" && p.name === "key")
return false;
if (p.name === "property") return false;
return true;
})
.size() > 0
);
};
// Caveat, this doesn't work with annonymously exported class declarations.
const isUsedInDecorators = () => {
// one could probably cache these, but I'm lazy.
let used = false;
root.find(j.ClassDeclaration).forEach((klass) => {
used =
used ||
(klass.node.decorators &&
j(klass.node.decorators)
.find(j.Identifier, { name: varName })
.filter((p) => {
if (p.parentPath.value.type === "Property" && p.name === "key")
return false;
if (p.name === "property") return false;
return true;
})
.size() > 0);
});
return used;
};
if (!(isUsedInScopes() || isUsedInDecorators())) {
j(importSpecifier).remove();
return true;
}
return false;
};
const removeUnusedDefaultImport = (importDeclaration) => {
return (
j(importDeclaration)
.find(j.ImportDefaultSpecifier)
.filter((s) => removeIfUnused(s, importDeclaration))
.size() > 0
);
};
const removeUnusedNonDefaultImports = (importDeclaration) => {
return (
j(importDeclaration)
.find(j.ImportSpecifier)
.filter((s) => removeIfUnused(s, importDeclaration))
.size() > 0
);
};
// Return True if somethin was transformed.
const processImportDeclaration = (importDeclaration) => {
// e.g. import 'styles.css'; // please Don't Touch these imports!
if (importDeclaration.value.specifiers.length === 0) return false;
const hadUnusedDefaultImport = removeUnusedDefaultImport(importDeclaration);
const hadUnusedNonDefaultImports =
removeUnusedNonDefaultImports(importDeclaration);
if (importDeclaration.value.specifiers.length === 0) {
j(importDeclaration).remove();
return true;
}
return hadUnusedDefaultImport || hadUnusedNonDefaultImports;
};
return root
.find(j.ImportDeclaration)
.filter(processImportDeclaration)
.size() > 0
? root.toSource(options.printOptions || { quote: "single" })
: null;
}