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

fix: dont strip type keyword from types imported from node modules #321

Open
wants to merge 2 commits into
base: master
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/bundle-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,7 @@ export function generateDtsBundle(entries: readonly EntryPointConfig[], options:
importItem = {
defaultImports: new Set(),
namedImports: new Map(),
typeImports: new Map(),
nsImport: null,
requireImports: new Set(),
reExports: new Map(),
Expand All @@ -660,10 +661,14 @@ export function generateDtsBundle(entries: readonly EntryPointConfig[], options:
importItem.requireImports.add(collisionsResolver.addTopLevelIdentifier(preferredLocalName));
}

function addNamedImport(importItem: ModuleImportsSet, preferredLocalName: ts.Identifier, importedIdentifier: ts.Identifier): void {
function addNamedImport(importItem: ModuleImportsSet, preferredLocalName: ts.Identifier, importedIdentifier: ts.Identifier, typeImportOrExport: boolean): void {
const newLocalName = collisionsResolver.addTopLevelIdentifier(preferredLocalName);
const importedName = importedIdentifier.text;
importItem.namedImports.set(newLocalName, importedName);
if (typeImportOrExport) {
importItem.typeImports.set(newLocalName, importedName);
} else {
importItem.namedImports.set(newLocalName, importedName);
}
}

function addReExport(importItem: ModuleImportsSet, moduleExportedName: string, reExportedName: string): void {
Expand Down Expand Up @@ -698,7 +703,8 @@ export function generateDtsBundle(entries: readonly EntryPointConfig[], options:

if (ts.isExportSpecifier(imp)) {
// export { El1, El2 as ExportedName } from 'module';
addNamedImport(importItem, imp.name, imp.propertyName || imp.name);
// export { El1, type El2 as ExportedName } from 'module';
addNamedImport(importItem, imp.name, imp.propertyName || imp.name, ts.isTypeOnlyExportDeclaration(imp));
return;
}

Expand All @@ -715,8 +721,9 @@ export function generateDtsBundle(entries: readonly EntryPointConfig[], options:
}

if (ts.isImportSpecifier(imp)) {
// import { type ImportedType } from 'module';
// import { El1, El2 as ImportedName } from 'module';
addNamedImport(importItem, imp.name, imp.propertyName || imp.name);
addNamedImport(importItem, imp.name, imp.propertyName || imp.name, ts.isTypeOnlyImportDeclaration(imp));
return;
}

Expand Down
16 changes: 16 additions & 0 deletions src/generate-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface ModuleImportsSet {
defaultImports: Set<string>;
nsImport: string | null;
namedImports: Map<string, string>;
typeImports: Map<string, string>;
requireImports: Set<string>;
reExports: Map<string, string>;
}
Expand Down Expand Up @@ -328,6 +329,21 @@ function generateImports(libraryName: string, imports: ModuleImportsSet): string
Array.from(imports.requireImports).sort().forEach((importName: string) => result.push(`import ${importName} = require('${libraryName}');`));
Array.from(imports.defaultImports).sort().forEach((importName: string) => result.push(`import ${importName} ${fromEnding}`));

// For each type-only import, check if it exists in the `namedImports` map and remove it
// otherwise we might end up with a type import and a regular import in the bundle.
for (const key of imports.typeImports.keys()) {
imports.namedImports.delete(key);
}
Comment on lines +332 to +336
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what I was afraid of. this will produce wrong output in the following case (or similar, I didn't check exactly this code but it should give you the idea):

// index.ts
import { MyClass } from 'some-lib';
import { ParentType } from './other';

export class Foo extends MyClass {
    field: ParentType;
}
// other.ts
import { type MyClass } from 'some-lib';

export type ParentType = MyClass;

Technically if a type was used as a "value", then it should be imported as a "value" even if there are imports of as a "type". But on the other side, there are cases where you might have mixed imports and mixed usage, and then re-export of "type" import but if we import it as "value" then it might be re-exported with a wrong meaning:

// index.ts
import type { MyClass } from 'some-lib';
import { FooBar } from './other';

export type MyClassType = MyClass;
// other.ts
import { MyClass } from 'some-lib';

export class FooBar extends MyClass {}

In this case the output might be the following:

import { MyClass } from 'some-lib';

export type MyClassType = MyClass;
export class FooBar extends MyClass {}

which looks correct, but it might have implications in other places (I need to play with this more to give you an example if there is one). Or it could be

import type { MyClass } from 'some-lib';

export type MyClassType = MyClass;
export class FooBar extends MyClass {}

Which is broken because 'FooBar' cannot be used as a value because it was imported using 'import type'.

That's why #290 exists and why initially I thought that #320 is a duplicate and then re-opened, but it seems I'm leaning to think about it as about a duplicate aging based on said above...

The issue is that compiler doesn't tell you whether a symbol/node was originally value but was used a type or anything like that (see microsoft/TypeScript#57032 for more context).

Copy link
Author

@egilsster egilsster May 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great reply! Haven't had time to digest but can hopefully sit down and think about this and push something. Appreciated!

It does look like we kinda need what's noted in the TypeScript issue. Will dig around and see what we can use otherwise.


if (imports.typeImports.size !== 0) {
result.push(`import { type ${
Array.from(imports.typeImports.entries())
.map(([localName, importedName]: [string, string]) => renamedImportValue(importedName, localName))
.sort()
.join(', type ')
Comment on lines +339 to +343
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like it can be replaced with just import type {} syntax instead?

} } ${fromEnding}`);
}

if (imports.namedImports.size !== 0) {
result.push(`import { ${
Array.from(imports.namedImports.entries())
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/test-cases/import-type-from-deps/output.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { InterfaceWithFields } from 'fake-package';
import { type InterfaceWithFields } from 'fake-package';

export declare type FakePackageType = InterfaceWithFields | string;
export type TestType = InterfaceWithFields | FakePackageType;
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/test-cases/preserve-type-imports/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { TestCaseConfig } from '../test-case-config';

const config: TestCaseConfig = {};

export = config;
1 change: 1 addition & 0 deletions tests/e2e/test-cases/preserve-type-imports/index.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require('../run-test-case').runTestCase(__dirname);
6 changes: 6 additions & 0 deletions tests/e2e/test-cases/preserve-type-imports/input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { Diagnostic, AffectedFileResult as RenamedImport } from "typescript";
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh please try to avoid using types from any of dependencies - they tend to change between releases and it will cause tests to fail without changing (almost) anything. If you need some specific pattern of a package, you can add it here https://github.com/timocov/dts-bundle-generator/tree/master/tests/e2e/test-cases/node_modules or use any existing one there


export type MyType = {
value: Diagnostic;
alias: RenamedImport<number>
};
8 changes: 8 additions & 0 deletions tests/e2e/test-cases/preserve-type-imports/output.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type AffectedFileResult as RenamedImport, type Diagnostic } from 'typescript';

export type MyType = {
value: Diagnostic;
alias: RenamedImport<number>;
};

export {};
6 changes: 6 additions & 0 deletions tests/e2e/test-cases/preserve-type-imports/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"verbatimModuleSyntax": true
}
}