Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CodeFix and Diagnostic for Unnecessary Named Import #61219

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48121,6 +48121,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
checkAliasSymbol(node);
if (node.kind === SyntaxKind.ImportSpecifier) {
checkModuleExportName(node.propertyName);

// Check for duplicate import names
const importSpecifier = node;
const namecheck = getTextOfIdentifierOrLiteral(importSpecifier.name);
const propertyNamecheck = importSpecifier.propertyName ? getTextOfIdentifierOrLiteral(importSpecifier.propertyName) : "";

if (namecheck === propertyNamecheck) {
errorOrSuggestion(/*isError*/ false, importSpecifier, Diagnostics.Redundant_named_import_0, namecheck);
}

if (
moduleExportNameIsDefault(node.propertyName || node.name) &&
getESModuleInterop(compilerOptions) &&
Expand Down
13 changes: 13 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -5337,6 +5337,11 @@
"category": "Error",
"code": 6189
},
"Redundant named import '{0}'.": {
"category": "Suggestion",
"code": 6190,
"reportsUnnecessary": true
},
"Whether to keep outdated console output in watch mode instead of clearing the screen.": {
"category": "Message",
"code": 6191
Expand Down Expand Up @@ -8267,6 +8272,14 @@
"category": "Message",
"code": 95197
},
"Simplify redundant import '{0}'": {
"category": "Message",
"code": 95198
},
"Simplify all redundant imports": {
"category": "Message",
"code": 95199
},

"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
Expand Down
1 change: 1 addition & 0 deletions src/services/_namespaces/ts.codefix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,4 @@ export * from "../codefixes/splitTypeOnlyImport.js";
export * from "../codefixes/convertConstToLet.js";
export * from "../codefixes/fixExpectedComma.js";
export * from "../codefixes/fixAddVoidToPromise.js";
export * from "../codefixes/removeUnnecessaryNamedImport.js";
53 changes: 53 additions & 0 deletions src/services/codefixes/removeUnnecessaryNamedImport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
codeFixAll,
createCodeFixAction,
registerCodeFix,
} from "../_namespaces/ts.codefix.js";
import {
Diagnostics,
factory,
getTokenAtPosition,
isImportSpecifier,
SourceFile,
textChanges,
TextSpan,
tryCast,
} from "../_namespaces/ts.js";

const fixId = "removeUnnecessaryNamedImport";
const errorCodes = [
Diagnostics.Redundant_named_import_0.code,
];

registerCodeFix({
errorCodes,
getCodeActions: function getCodeActionsToRemoveUnnecessaryNamedImport(context) {
const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span));
const token = getTokenAtPosition(context.sourceFile, context.span.start);
const importSpecifier = tryCast(token.parent, isImportSpecifier);

if (!importSpecifier) {
return;
}

if (changes.length > 0) {
return [createCodeFixAction(fixId, changes, [Diagnostics.Simplify_redundant_import_0, importSpecifier.name.text], fixId, Diagnostics.Simplify_all_redundant_imports)];
}
},
fixIds: [fixId],
getAllCodeActions: context => {
return codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag));
},
});

function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, span: TextSpan) {
const token = getTokenAtPosition(sourceFile, span.start);
const importSpecifier = tryCast(token.parent, isImportSpecifier);
if (!importSpecifier) {
return;
}

if (importSpecifier.propertyName && importSpecifier.propertyName.text === importSpecifier.name.text) {
changeTracker.replaceNode(sourceFile, importSpecifier, factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ undefined, importSpecifier.name));
}
}
31 changes: 31 additions & 0 deletions tests/cases/fourslash/codeFixRemoveUnnecessaryNamedImports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/// <reference path="fourslash.ts" />

// @filename: /a.ts
////export const foo = () => console.log('Hello world!');
////export const bar = () => console.log('Hello world!');

// @filename: /b.ts
////import { foo as foo, bar as bar } from "./a";
////foo();
////bar();

goTo.file("/b.ts");

verify.codeFix({
description: 'Simplify redundant import \'foo\'',
index: 0,
newFileContent:
`import { foo, bar as bar } from "./a";
foo();
bar();`
});

verify.codeFixAll({
fixAllDescription: ts.Diagnostics.Simplify_all_redundant_imports.message,
fixId: "removeUnnecessaryNamedImport",
newFileContent:
`import { foo, bar } from "./a";
foo();
bar();`
});

21 changes: 21 additions & 0 deletions tests/cases/fourslash/redundantImportDiagnostic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/// <reference path="fourslash.ts" />

// @filename: /a.ts
//// export const bar = () => console.log('Hello world!');

// @filename: /b.ts
//// import { bar as bar } from "./a";
//// bar();


goTo.file("/b.ts");


verify.getSuggestionDiagnostics([
{
message: "Redundant named import 'bar'.",
code: ts.Diagnostics.Redundant_named_import_0.code,
range: {pos: 9, end: 19, fileName:"/b.ts"},
reportsUnnecessary: true,
}
]);