diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 99b677ebd3..96f4b7ad4b 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -133,7 +133,7 @@ namespace ts.codefix { const symbolIdActionMap = new ImportCodeActionMap(); // this is a module id -> module import declaration map - const cachedImportDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[][] = []; + const cachedImportDeclarations: AnyImportSyntax[][] = []; let lastImportDeclaration: Node; const currentTokenMeaning = getMeaningFromLocation(token); @@ -199,28 +199,20 @@ namespace ts.codefix { return cached; } - const existingDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[] = []; - for (const importModuleSpecifier of sourceFile.imports) { - const importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); - } - } + const existingDeclarations = mapDefined(sourceFile.imports, importModuleSpecifier => + checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined); cachedImportDeclarations[moduleSymbolId] = existingDeclarations; return existingDeclarations; - function getImportDeclaration(moduleSpecifier: LiteralExpression) { - let node: Node = moduleSpecifier; - while (node) { - if (node.kind === SyntaxKind.ImportDeclaration) { - return node; - } - if (node.kind === SyntaxKind.ImportEqualsDeclaration) { - return node; - } - node = node.parent; + function getImportDeclaration({ parent }: LiteralExpression): AnyImportSyntax { + switch (parent.kind) { + case SyntaxKind.ImportDeclaration: + return parent as ImportDeclaration; + case SyntaxKind.ExternalModuleReference: + return (parent as ExternalModuleReference).parent; + default: + return undefined; } - return undefined; } } diff --git a/tests/cases/fourslash/importNameCodeFixReExport.ts b/tests/cases/fourslash/importNameCodeFixReExport.ts new file mode 100644 index 0000000000..c77d32cc45 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixReExport.ts @@ -0,0 +1,16 @@ +/// + +// Test that we are not fooled by a re-export existing in the file already + +// @Filename: /a.ts +////export const x = 0"; + +// @Filename: /b.ts +////[|export { x } from "./a"; +////x;|] + +goTo.file("/b.ts"); +verify.rangeAfterCodeFix(`import { x } from "./a"; + +export { x } from "./a"; +x;`, /*includeWhiteSpace*/ true);