Skip to content

Commit

Permalink
fix: handle removeDefaultImport with type only import (#1547)
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret authored Jun 23, 2024
1 parent b3d01c8 commit 1cf6a6b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
23 changes: 17 additions & 6 deletions packages/ts-morph/src/compiler/ast/module/ImportDeclaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,13 +237,24 @@ export class ImportDeclaration extends ImportDeclarationBase<ts.ImportDeclaratio
if (defaultImport == null)
return this;

const hasOnlyDefaultImport = importClause.getChildCount() === 1;
const hasOnlyDefaultImport = importClause.getNamedBindings() == null;
if (hasOnlyDefaultImport) {
removeChildren({
children: [importClause, importClause.getNextSiblingIfKindOrThrow(SyntaxKind.FromKeyword)],
removePrecedingSpaces: true,
removePrecedingNewLines: true,
});
if (importClause.isTypeOnly()) {
insertIntoParentTextRange({
parent: importClause,
newText: "{}",
insertPos: defaultImport.getStart(),
replacing: {
textLength: defaultImport.getWidth(),
},
});
} else {
removeChildren({
children: [importClause, importClause.getNextSiblingIfKindOrThrow(SyntaxKind.FromKeyword)],
removePrecedingSpaces: true,
removePrecedingNewLines: true,
});
}
} else {
removeChildren({
children: [defaultImport, defaultImport.getNextSiblingIfKindOrThrow(SyntaxKind.CommaToken)],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,14 @@ describe("ImportDeclaration", () => {
it("should remove it when named imports exists", () => {
doTest(`import name, { test } from './file';`, `import { test } from './file';`);
});

it("should handle import type", () => {
doTest(`import type test from './file';`, `import type {} from './file';`);
});

it("should handle import type with named imports", () => {
doTest(`import type test, { other } from './file';`, `import type { other } from './file';`);
});
});

describe(nameof<ImportDeclaration>("removeNamespaceImport"), () => {
Expand Down

0 comments on commit 1cf6a6b

Please sign in to comment.