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: correct .d.cts default export type #458

Merged
merged 2 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading