@@ -5,11 +5,19 @@ namespace ts.codefix {
5
5
const errorCodes = [
6
6
Diagnostics . _0_is_declared_but_its_value_is_never_read . code ,
7
7
Diagnostics . Property_0_is_declared_but_its_value_is_never_read . code ,
8
+ Diagnostics . All_imports_in_import_declaration_are_unused . code ,
8
9
] ;
9
10
registerCodeFix ( {
10
11
errorCodes,
11
12
getCodeActions ( context ) {
12
- const { sourceFile } = context ;
13
+ const { errorCode, sourceFile } = context ;
14
+ const importDecl = tryGetFullImport ( sourceFile , context . span . start ) ;
15
+ if ( importDecl ) {
16
+ const description = formatStringFromArgs ( getLocaleSpecificMessage ( Diagnostics . Remove_import_from_0 ) , [ showModuleSpecifier ( importDecl ) ] ) ;
17
+ const changes = textChanges . ChangeTracker . with ( context , t => t . deleteNode ( sourceFile , importDecl ) ) ;
18
+ return [ { description, changes, fixId : fixIdDelete } ] ;
19
+ }
20
+
13
21
const token = getToken ( sourceFile , textSpanEnd ( context . span ) ) ;
14
22
const result : CodeFixAction [ ] = [ ] ;
15
23
@@ -19,7 +27,7 @@ namespace ts.codefix {
19
27
result . push ( { description, changes : deletion , fixId : fixIdDelete } ) ;
20
28
}
21
29
22
- const prefix = textChanges . ChangeTracker . with ( context , t => tryPrefixDeclaration ( t , context . errorCode , sourceFile , token ) ) ;
30
+ const prefix = textChanges . ChangeTracker . with ( context , t => tryPrefixDeclaration ( t , errorCode , sourceFile , token ) ) ;
23
31
if ( prefix . length ) {
24
32
const description = formatStringFromArgs ( getLocaleSpecificMessage ( Diagnostics . Prefix_0_with_an_underscore ) , [ token . getText ( ) ] ) ;
25
33
result . push ( { description, changes : prefix , fixId : fixIdPrefix } ) ;
@@ -38,14 +46,26 @@ namespace ts.codefix {
38
46
}
39
47
break ;
40
48
case fixIdDelete :
41
- tryDeleteDeclaration ( changes , sourceFile , token ) ;
49
+ const importDecl = tryGetFullImport ( diag . file ! , diag . start ! ) ;
50
+ if ( importDecl ) {
51
+ changes . deleteNode ( sourceFile , importDecl ) ;
52
+ }
53
+ else {
54
+ tryDeleteDeclaration ( changes , sourceFile , token ) ;
55
+ }
42
56
break ;
43
57
default :
44
58
Debug . fail ( JSON . stringify ( context . fixId ) ) ;
45
59
}
46
60
} ) ,
47
61
} ) ;
48
62
63
+ // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
64
+ function tryGetFullImport ( sourceFile : SourceFile , pos : number ) : ImportDeclaration | undefined {
65
+ const startToken = getTokenAtPosition ( sourceFile , pos , /*includeJsDocComment*/ false ) ;
66
+ return startToken . kind === SyntaxKind . ImportKeyword ? tryCast ( startToken . parent , isImportDeclaration ) : undefined ;
67
+ }
68
+
49
69
function getToken ( sourceFile : SourceFile , pos : number ) : Node {
50
70
const token = findPrecedingToken ( pos , sourceFile ) ;
51
71
// this handles var ["computed"] = 12;
0 commit comments