|
1 | 1 | /**
|
| 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. |
2 | 8 | *@param {Object} context
|
3 | 9 | *@param {import('jscodeshift').JSCodeshift} context.j
|
4 | 10 | *@param {ReturnType<import('jscodeshift').Core>} context.root
|
5 | 11 | */
|
6 |
| -functionremoveExtraneousImport({ root, j},name){ |
7 |
| -constlocalUsages=root.find(j.Identifier,{ name}) |
8 |
| -if(localUsages.length===1){ |
9 |
| -constimportDecl=localUsages.closest(j.ImportDeclaration) |
10 |
| - |
11 |
| -if(!importDecl.length){ |
12 |
| -return |
13 |
| -} |
| 12 | +module.exports=functionremoveExtraneousImport({ root, j},name){ |
| 13 | +constisPathEqual=(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 | +functionfilterAndRemoveImports(path){ |
| 22 | +constusages=j(path) |
| 23 | +.closestScope() |
| 24 | +.find(j.Identifier,{ name}) |
| 25 | +// Ignore the specifier |
| 26 | +.filter(identifierPath=>{ |
| 27 | +constparent=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 | +constparent=identifierPath.parent.node |
| 36 | +return!( |
| 37 | +j.MemberExpression.check(parent)&& |
| 38 | +parent.property===identifierPath.node |
| 39 | +) |
| 40 | +}) |
14 | 41 |
|
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() |
20 | 44 | }
|
21 | 45 | }
|
| 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) |
22 | 62 | }
|