dts-plugins.ts
This file
Path
build/dts-plugins.ts
55 lines · 1.8 KiB · TypeScript
Last changed by
fix(build): keep internal types private in bundled d.ts and avoid a self-referencing JSX.IntrinsicElements (#5485)Yusuke Wadabefore adoptionbe1f749
History of this fileTake it
fix(build): keep internal types private in bundled d.ts and avoid a self-referencing JSX.IntrinsicElements (#5485)Yusuke Wadabefore adoptionbe1f749
lines 1–55why, one step back1import { parse } from 'rolldown/utils'2import type { TsdownPluginOption } from 'vite-plus/pack'34const DECLARATION_TYPES = new Set([5 'TSTypeAliasDeclaration',6 'TSInterfaceDeclaration',7 'TSDeclareFunction',8 'TSEnumDeclaration',9 'TSModuleDeclaration',10 'VariableDeclaration',11 'ClassDeclaration',12 'FunctionDeclaration',13])1415/**16 * Append `export {}` to an emitted `.d.ts` module that has top-level declarations without `export`,17 * exactly as tsc does when it emits declaration files.18 *19 * Without it TypeScript treats every top-level declaration of a `.d.ts` module as exported, so20 * consumers' declaration emit may reference internal aliases through `<pkg>/dist/...`, which is21 * not reachable via the package exports (TS2883). The bundled dts emit does not add it.22 */23export const appendExportEmptyToDts: TsdownPluginOption = {24 name: 'hono:append-export-empty-to-dts',25 async renderChunk(code, chunk) {26 if (!chunk.fileName.endsWith('.d.ts')) {27 return28 }2930 const { body } = (await parse(chunk.fileName, code)).program3132 let isModule = false33 let hasPrivateDeclaration = false34 for (const statement of body) {35 if (statement.type === 'ImportDeclaration' || statement.type.startsWith('Export')) {36 isModule = true37 // `export {}` or `export = x` already turns the implicit export off38 if (39 (statement.type === 'ExportNamedDeclaration' &&40 !statement.declaration &&41 statement.specifiers.length === 0) ||42 statement.type === 'TSExportAssignment'43 ) {44 return45 }46 } else if (DECLARATION_TYPES.has(statement.type)) {47 hasPrivateDeclaration = true48 }49 }5051 if (isModule && hasPrivateDeclaration) {52 return `${code}\nexport {};\n`53 }54 },55}