diff --git a/src/builders/rollup/build.ts b/src/builders/rollup/build.ts index 8b3d6f40..f7c49889 100644 --- a/src/builders/rollup/build.ts +++ b/src/builders/rollup/build.ts @@ -9,6 +9,7 @@ import { getRollupOptions } from "./config"; import { getChunkFilename } from "./utils"; import { rollupStub } from "./stub"; import { rollupWatch } from "./watch"; +import { fixCJSExportTypePlugin } from "./plugins/cjs"; export async function rollupBuild(ctx: BuildContext): Promise { // Stub mode @@ -81,7 +82,8 @@ export async function rollupBuild(ctx: BuildContext): Promise { ...rollupOptions.plugins, dts(ctx.options.rollup.dts), removeShebangPlugin(), - ]; + ctx.options.rollup.emitCJS && fixCJSExportTypePlugin(), + ].filter(Boolean); await ctx.hooks.callHook("rollup:dts:options", ctx, rollupOptions); const typesBuild = await rollup(rollupOptions); diff --git a/src/builders/rollup/plugins/cjs.ts b/src/builders/rollup/plugins/cjs.ts index 2bba6d0e..5edfa5bd 100644 --- a/src/builders/rollup/plugins/cjs.ts +++ b/src/builders/rollup/plugins/cjs.ts @@ -14,6 +14,29 @@ export function cjsPlugin(_opts?: any): Plugin { } as Plugin; } +// Ported from https://github.com/egoist/tsup/blob/cd03e1e00ec2bd6676ae1837cbc7e618ab6a2362/src/rollup.ts#L92-L109 +export function fixCJSExportTypePlugin(): Plugin { + return { + name: "unbuild-fix-cjs-export-type", + renderChunk(code, info, opts) { + if ( + info.type !== "chunk" || + !info.fileName.endsWith(".d.cts") || + !info.isEntry || + info.exports?.length !== 1 || + info.exports[0] !== "default" + ) { + return; + } + + return code.replace( + /(?<=(?<=[;}]|^)\s*export\s*){\s*([\w$]+)\s*as\s+default\s*}/, + `= $1`, + ); + }, + } as Plugin; +} + const CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/; const CJSShim = `