Skip to content

Commit

Permalink
feat: use fix-dts-default-cjs-exports to transform cjs types (#513)
Browse files Browse the repository at this point in the history
  • Loading branch information
userquin authored Feb 26, 2025
1 parent 045ebf2 commit 3edb456
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 20 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"consola": "^3.4.0",
"defu": "^6.1.4",
"esbuild": "^0.25.0",
"fix-dts-default-cjs-exports": "^1.0.0",
"hookable": "^5.5.3",
"jiti": "^2.4.2",
"magic-string": "^0.30.17",
Expand Down
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/builders/rollup/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export async function rollupBuild(ctx: BuildContext): Promise<void> {
...rollupOptions.plugins,
dts(ctx.options.rollup.dts),
removeShebangPlugin(),
ctx.options.rollup.emitCJS && fixCJSExportTypePlugin(),
ctx.options.rollup.emitCJS && fixCJSExportTypePlugin(ctx),
].filter(
(plugin) =>
/**
Expand Down
36 changes: 17 additions & 19 deletions src/builders/rollup/plugins/cjs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { Plugin } from "rollup";
import { findStaticImports } from "mlly";
import MagicString from "magic-string";
import type { BuildContext } from "../../../types.ts";
import { FixDtsDefaultCjsExportsPlugin } from "fix-dts-default-cjs-exports/rollup";

export function cjsPlugin(_opts?: any): Plugin {
return {
Expand All @@ -14,27 +16,23 @@ 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`,
export function fixCJSExportTypePlugin(ctx: BuildContext): Plugin {
const regexp =
ctx.options.declaration === "node16"
? /\.d\.cts$/ // d.cts only
: /\.d\.c?ts$/; // d.ts and d.cts
return FixDtsDefaultCjsExportsPlugin({
warn: (msg) => ctx.warnings.add(msg),
matcher: (info) => {
return (
info.type === "chunk" &&
info.exports?.length > 0 &&
info.exports.includes("default") &&
regexp.test(info.fileName) &&
info.isEntry
);
},
} as Plugin;
}) as Plugin;
}

const CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/;
Expand Down

0 comments on commit 3edb456

Please sign in to comment.