Skip to content

Commit

Permalink
fix: fix the .d.cts default export type
Browse files Browse the repository at this point in the history
  • Loading branch information
kricsleo committed Dec 17, 2024
1 parent a9893a2 commit 908c0c0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/builders/rollup/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
// Stub mode
Expand Down Expand Up @@ -81,7 +82,8 @@ export async function rollupBuild(ctx: BuildContext): Promise<void> {
...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);
Expand Down
23 changes: 23 additions & 0 deletions src/builders/rollup/plugins/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
Expand Down

0 comments on commit 908c0c0

Please sign in to comment.