From 9d5d4109d4033b8fe3dbb112ca53eced1fcd4348 Mon Sep 17 00:00:00 2001 From: JohnAlbin Date: Thu, 19 Oct 2023 20:59:32 +0800 Subject: [PATCH] build(next-drupal): add .d.cts type definition files --- packages/next-drupal/.npmignore | 1 + packages/next-drupal/package.json | 13 +++++++++++++ packages/next-drupal/postBuild.js | 22 ++++++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 packages/next-drupal/postBuild.js diff --git a/packages/next-drupal/.npmignore b/packages/next-drupal/.npmignore index 7299177ef..c7a87b5f8 100644 --- a/packages/next-drupal/.npmignore +++ b/packages/next-drupal/.npmignore @@ -1,4 +1,5 @@ /coverage /CHANGELOG.md +/postBuild.js /tests /tsconfig.json diff --git a/packages/next-drupal/package.json b/packages/next-drupal/package.json index ad0b87ba2..cbac2aad5 100644 --- a/packages/next-drupal/package.json +++ b/packages/next-drupal/package.json @@ -7,6 +7,18 @@ "type": "module", "main": "dist/index.cjs", "module": "dist/index.modern.js", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.modern.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, "types": "dist/index.d.ts", "license": "MIT", "publishConfig": { @@ -18,6 +30,7 @@ }, "scripts": { "prepare": "microbundle --no-compress --jsx React.createElement --format modern,cjs", + "postprepare": "node postBuild.js", "dev": "microbundle watch --no-compress --jsx React.createElement --format modern,cjs", "test": "jest" }, diff --git a/packages/next-drupal/postBuild.js b/packages/next-drupal/postBuild.js new file mode 100644 index 000000000..4dc9eb99d --- /dev/null +++ b/packages/next-drupal/postBuild.js @@ -0,0 +1,22 @@ +import { readdir, copyFile } from "node:fs/promises" + +const files = await readdir("./dist") +const tasks = [] +for (const file of files) { + if (file.endsWith(".modern.js")) { + const base = file.replace(/\.modern\.js$/, "") + + // Make a duplicate of the type definitions. + // + // From the TypeScript docs: + // + // "It’s important to note that the CommonJS entrypoint and the ES module + // entrypoint each needs its own declaration file, even if the contents are + // the same between them." + // + // @see https://www.typescriptlang.org/docs/handbook/esm-node.html#packagejson-exports-imports-and-self-referencing + tasks.push(copyFile(`./dist/${base}.d.ts`, `./dist/${base}.d.cts`)) + } +} +await Promise.all(tasks) +console.log(`Created unique *.d.cts files for CommonJS build.`)