From 1179618f34dfca705d11318d80bff63f444cc161 Mon Sep 17 00:00:00 2001 From: Connor Pearson Date: Fri, 13 Dec 2024 22:26:10 +0100 Subject: [PATCH] feat: support dynamic imports with addRelativeDeclarationExtensions (#267) --- src/utils/dts.ts | 31 +++++++++++++++++++++++++++++-- test/fixture/src/star/index.ts | 4 ++++ test/index.test.ts | 3 +++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/utils/dts.ts b/src/utils/dts.ts index 7aeb57a6..98d4e8fb 100644 --- a/src/utils/dts.ts +++ b/src/utils/dts.ts @@ -1,5 +1,10 @@ import { statSync } from "node:fs"; -import { findStaticImports, findExports, findTypeExports } from "mlly"; +import { + findStaticImports, + findDynamicImports, + findExports, + findTypeExports, +} from "mlly"; import { resolve } from "pathe"; import type { TSConfig } from "pkg-types"; import type { MkdistOptions } from "../make"; @@ -69,7 +74,29 @@ export function extractDeclarations( const imports = findStaticImports(contents); const exports = findExports(contents); const typeExports = findTypeExports(contents); - for (const spec of [...exports, ...typeExports, ...imports]) { + const dynamicImports = findDynamicImports(contents).map( + (dynamicImport) => { + let specifier: string | undefined; + try { + const value = JSON.parse(dynamicImport.expression); + if (typeof value === "string") { + specifier = value; + } + } catch { + // ignore the error + } + return { + code: dynamicImport.code, + specifier, + }; + }, + ); + for (const spec of [ + ...exports, + ...typeExports, + ...imports, + ...dynamicImports, + ]) { if (!spec.specifier || !RELATIVE_RE.test(spec.specifier)) { continue; } diff --git a/test/fixture/src/star/index.ts b/test/fixture/src/star/index.ts index c6dcf0b6..939a39ea 100644 --- a/test/fixture/src/star/index.ts +++ b/test/fixture/src/star/index.ts @@ -1,2 +1,6 @@ export * from "./other"; export type { Other } from "./other"; + +export function wonder(twinkle: import("./other").Other): string { + return twinkle; +} diff --git a/test/index.test.ts b/test/index.test.ts index f2dc0ddc..bf74fb5a 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -160,6 +160,7 @@ describe("mkdist", () => { .toMatchInlineSnapshot(` "export * from "./other.js"; export type { Other } from "./other.js"; + export declare function wonder(twinkle: import("./other.js").Other): string; " `); @@ -613,6 +614,7 @@ describe("mkdist with vue-tsc v1", () => { .toMatchInlineSnapshot(` "export * from "./other.js"; export type { Other } from "./other.js"; + export declare function wonder(twinkle: import("./other.js").Other): string; " `); expect( @@ -870,6 +872,7 @@ describe("mkdist with vue-tsc ~v2.0.21", () => { .toMatchInlineSnapshot(` "export * from "./other.js"; export type { Other } from "./other.js"; + export declare function wonder(twinkle: import("./other.js").Other): string; " `); expect(