Skip to content

Commit 660cace

Browse files
committed
fix: fix remove-extraneous-import implementation
1 parent 40abe93 commit 660cace

File tree

2 files changed

+56
-13
lines changed

2 files changed

+56
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import 'vue';
2+
import 'vue-router';
3+
import 'Vuex';
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,62 @@
11
/**
2+
* Note:
3+
* here we don't completely remove the import declaration statement
4+
* if all import specifiers are removed.
5+
* For example, `import Vue from 'vue'`,
6+
* if `Vue` is unused, the statement would become `import 'vue'`.
7+
* It is because we are not sure if the module contains any side effects.
28
* @param {Object} context
39
* @param {import('jscodeshift').JSCodeshift} context.j
410
* @param {ReturnType<import('jscodeshift').Core>} context.root
511
*/
6-
function removeExtraneousImport({ root, j }, name) {
7-
const localUsages = root.find(j.Identifier, { name })
8-
if (localUsages.length === 1) {
9-
const importDecl = localUsages.closest(j.ImportDeclaration)
10-
11-
if (!importDecl.length) {
12-
return
13-
}
12+
module.exports = function removeExtraneousImport({ root, j }, name) {
13+
const isPathEqual = (path1, path2) => {
14+
return (
15+
path1.node.start === path2.node.start && path1.node.end === path2.node.end
16+
)
17+
}
18+
/**
19+
* @param {import('jscodeshift').ASTPath} path
20+
*/
21+
function filterAndRemoveImports(path) {
22+
const usages = j(path)
23+
.closestScope()
24+
.find(j.Identifier, { name })
25+
// Ignore the specifier
26+
.filter(identifierPath => {
27+
const parent = identifierPath.parent.node
28+
return (
29+
!j.ImportDefaultSpecifier.check(parent) &&
30+
!j.ImportSpecifier.check(parent)
31+
)
32+
})
33+
// Ignore properties in MemberExpressions
34+
.filter(identifierPath => {
35+
const parent = identifierPath.parent.node
36+
return !(
37+
j.MemberExpression.check(parent) &&
38+
parent.property === identifierPath.node
39+
)
40+
})
1441

15-
if (importDecl.get(0).node.specifiers.length === 1) {
16-
importDecl.remove()
17-
} else {
18-
localUsages.closest(j.ImportSpecifier).remove()
19-
localUsages.closest(j.ImportDefaultSpecifier).remove()
42+
if (!usages.length) {
43+
j(path).remove()
2044
}
2145
}
46+
47+
root
48+
.find(j.ImportSpecifier, {
49+
local: {
50+
name
51+
}
52+
})
53+
.filter(filterAndRemoveImports)
54+
55+
root
56+
.find(j.ImportDefaultSpecifier, {
57+
local: {
58+
name
59+
}
60+
})
61+
.filter(filterAndRemoveImports)
2262
}

0 commit comments

Comments
 (0)