Skip to content

Commit 1cf6a6b

Browse files
authored
fix: handle removeDefaultImport with type only import (#1547)
1 parent b3d01c8 commit 1cf6a6b

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

packages/ts-morph/src/compiler/ast/module/ImportDeclaration.ts

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -237,13 +237,24 @@ export class ImportDeclaration extends ImportDeclarationBase<ts.ImportDeclaratio
237237
if (defaultImport == null)
238238
return this;
239239

240-
const hasOnlyDefaultImport = importClause.getChildCount() === 1;
240+
const hasOnlyDefaultImport = importClause.getNamedBindings() == null;
241241
if (hasOnlyDefaultImport) {
242-
removeChildren({
243-
children: [importClause, importClause.getNextSiblingIfKindOrThrow(SyntaxKind.FromKeyword)],
244-
removePrecedingSpaces: true,
245-
removePrecedingNewLines: true,
246-
});
242+
if (importClause.isTypeOnly()) {
243+
insertIntoParentTextRange({
244+
parent: importClause,
245+
newText: "{}",
246+
insertPos: defaultImport.getStart(),
247+
replacing: {
248+
textLength: defaultImport.getWidth(),
249+
},
250+
});
251+
} else {
252+
removeChildren({
253+
children: [importClause, importClause.getNextSiblingIfKindOrThrow(SyntaxKind.FromKeyword)],
254+
removePrecedingSpaces: true,
255+
removePrecedingNewLines: true,
256+
});
257+
}
247258
} else {
248259
removeChildren({
249260
children: [defaultImport, defaultImport.getNextSiblingIfKindOrThrow(SyntaxKind.CommaToken)],

packages/ts-morph/src/tests/compiler/ast/module/importDeclarationTests.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,14 @@ describe("ImportDeclaration", () => {
363363
it("should remove it when named imports exists", () => {
364364
doTest(`import name, { test } from './file';`, `import { test } from './file';`);
365365
});
366+
367+
it("should handle import type", () => {
368+
doTest(`import type test from './file';`, `import type {} from './file';`);
369+
});
370+
371+
it("should handle import type with named imports", () => {
372+
doTest(`import type test, { other } from './file';`, `import type { other } from './file';`);
373+
});
366374
});
367375

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

0 commit comments

Comments
 (0)