From 3811611c21744d757089b6eb90901f2cfec87124 Mon Sep 17 00:00:00 2001 From: ZHAO Jin-Xiang Date: Thu, 14 Sep 2023 13:23:18 +0800 Subject: [PATCH] fix: declaration option --- src/auto.ts | 6 ++++-- src/build.ts | 2 +- src/builder/rollup.ts | 19 ++++++++++++++----- test/fixture/build.config.ts | 2 +- test/fixture/build.preset.ts | 2 +- 5 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/auto.ts b/src/auto.ts index c70f9f27..22bd1ab3 100644 --- a/src/auto.ts +++ b/src/auto.ts @@ -30,8 +30,10 @@ export const autoPreset = definePreset(() => { if (res.cjs) { ctx.options.rollup.emitCJS = true; } - if (res.dts) { - ctx.options.declaration = res.dts; + if (ctx.options.declaration === undefined) { + // Enable auto detect based on "package.json" + // If "package.json" has "types" field, it will be "compatible", otherwise false. + ctx.options.declaration = res.dts ? "compatible" : false; } consola.info( "Automatically detected entries:", diff --git a/src/build.ts b/src/build.ts index 73eaa661..1319fda6 100644 --- a/src/build.ts +++ b/src/build.ts @@ -74,7 +74,7 @@ async function _build( rootDir, entries: [], clean: true, - declaration: false, + declaration: undefined, outDir: "dist", stub, stubOptions: { diff --git a/src/builder/rollup.ts b/src/builder/rollup.ts index 7fb94f77..7541a9b1 100644 --- a/src/builder/rollup.ts +++ b/src/builder/rollup.ts @@ -113,17 +113,26 @@ export async function rollupBuild(ctx: BuildContext) { ); // DTS Stub - await writeFile( - output + ".d.ts", - [ + if (ctx.options.declaration) { + const dtsContent = [ `export * from ${JSON.stringify(resolvedEntryWithoutExt)};`, hasDefaultExport ? `export { default } from ${JSON.stringify( resolvedEntryWithoutExt, )};` : "", - ].join("\n"), - ); + ].join("\n"); + + await writeFile(output + ".d.cts", dtsContent); + await writeFile(output + ".d.mts", dtsContent); + // .d.ts for node10 compatibility (TypeScript version < 4.7) + if ( + ctx.options.declaration === "compatible" || + ctx.options.declaration === true + ) { + await writeFile(output + ".d.ts", dtsContent); + } + } if (shebang) { await makeExecutable(output + ".cjs"); diff --git a/test/fixture/build.config.ts b/test/fixture/build.config.ts index 7be9cc24..42f435cc 100644 --- a/test/fixture/build.config.ts +++ b/test/fixture/build.config.ts @@ -22,7 +22,7 @@ export default defineBuildConfig([ entries: ["src/index"], outDir: "dist/min", sourcemap: true, - declaration: true, + declaration: "compatible", rollup: { esbuild: { minify: true, diff --git a/test/fixture/build.preset.ts b/test/fixture/build.preset.ts index 75224f99..60db3f07 100644 --- a/test/fixture/build.preset.ts +++ b/test/fixture/build.preset.ts @@ -1,7 +1,7 @@ import { definePreset } from "../../src"; export default definePreset({ - declaration: true, + declaration: "compatible", rollup: { cjsBridge: true, },