Don’t remove imports that are used for module augmentation, just remove their import clauses

This commit is contained in:
Andrew Branch 2019-05-20 14:49:28 -07:00
parent 0f15bda45f
commit 6faeee449d
No known key found for this signature in database
GPG Key ID: 22CCA4B120C427D2
3 changed files with 42 additions and 2 deletions

View File

@ -89,7 +89,7 @@ namespace ts.OrganizeImports {
const usedImports: ImportDeclaration[] = [];
for (const importDecl of oldImports) {
const {importClause} = importDecl;
const { importClause, moduleSpecifier } = importDecl;
if (!importClause) {
// Imports without import clauses are assumed to be included for their side effects and are not removed.
@ -125,6 +125,14 @@ namespace ts.OrganizeImports {
if (name || namedBindings) {
usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
}
// If a module is imported to be augmented, keep the import declaration, but without an import clause
else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
usedImports.push(createImportDeclaration(
importDecl.decorators,
importDecl.modifiers,
/*importClause*/ undefined,
moduleSpecifier));
}
}
return usedImports;
@ -135,6 +143,14 @@ namespace ts.OrganizeImports {
}
}
function hasModuleDeclarationMatchingSpecifier(sourceFile: SourceFile, moduleSpecifier: Expression) {
const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
return isString(moduleSpecifierText) && some(sourceFile.statements, statement =>
isModuleDeclaration(statement)
&& isStringLiteral(statement.name)
&& statement.name.text === moduleSpecifierText);
}
function getExternalModuleName(specifier: Expression) {
return specifier !== undefined && isStringLiteralLike(specifier)
? specifier.text

View File

@ -1,5 +1,5 @@
namespace ts {
describe("unittests:: services:: Organize imports", () => {
describe("unittests:: services:: organizeImports", () => {
describe("Sort imports", () => {
it("Sort - non-relative vs non-relative", () => {
assertSortsBefore(
@ -347,8 +347,10 @@ import { } from "lib";
{
path: "/test.d.ts",
content: `
import foo from 'foo';
import { Caseless } from 'caseless';
declare module 'foo' {}
declare module 'caseless' {
interface Caseless {
test(name: KeyType): boolean;

View File

@ -0,0 +1,22 @@
// ==ORIGINAL==
import foo from 'foo';
import { Caseless } from 'caseless';
declare module 'foo' {}
declare module 'caseless' {
interface Caseless {
test(name: KeyType): boolean;
}
}
// ==ORGANIZED==
import 'caseless';
import 'foo';
declare module 'foo' {}
declare module 'caseless' {
interface Caseless {
test(name: KeyType): boolean;
}
}