From b64b0a88ba278e841241a3c230861d167eee5915 Mon Sep 17 00:00:00 2001 From: Tatsunori Uchino Date: Tue, 21 Jan 2025 13:17:24 +0900 Subject: [PATCH] Use ESM entrypoint for `require(ESM)` (#16958) Co-authored-by: fisker Cheung --- changelog_unreleased/misc/16958.md | 5 +++++ package.json | 1 + scripts/build/build-package-json.js | 5 ++++- 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 changelog_unreleased/misc/16958.md diff --git a/changelog_unreleased/misc/16958.md b/changelog_unreleased/misc/16958.md new file mode 100644 index 000000000..e9d41630d --- /dev/null +++ b/changelog_unreleased/misc/16958.md @@ -0,0 +1,5 @@ +#### Use ESM entrypoint for `require(ESM)` (#16958 by @tats-u) + +Node.js 22.12 or later [can (experimentally) load ESM modules with `require` function](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) without runtime flags. This change enables `require` to load Prettier without the CommonJS entrypoint with almost only the ability to import the ESM entrypoint. + +The feature to load ES modules with `require` is not completely stable but can be used without ExperimentalWarning as of Node 22.13. diff --git a/package.json b/package.json index 434987fd5..9e57fab54 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "exports": { ".": { "types": "./src/index.d.ts", + "module-sync": "./src/index.js", "require": "./src/index.cjs", "default": "./src/index.js" }, diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js index 5f35e7c4c..ea185c32e 100644 --- a/scripts/build/build-package-json.js +++ b/scripts/build/build-package-json.js @@ -42,6 +42,7 @@ async function buildPackageJson({ file, files }) { exports: { ".": { types: "./index.d.ts", + "module-sync": "./index.mjs", require: "./index.cjs", browser: { import: "./standalone.mjs", @@ -55,12 +56,14 @@ async function buildPackageJson({ file, files }) { .filter((file) => file.output.format === "umd") .map((file) => { const basename = path.basename(file.output.file, ".js"); + const mjsPath = `./${file.output.file.replace(/\.js$/u, ".mjs")}`; return [ file.isPlugin ? `./plugins/${basename}` : `./${basename}`, { types: `./${file.output.file.replace(/\.js$/u, ".d.ts")}`, + "module-sync": mjsPath, require: `./${file.output.file}`, - default: `./${file.output.file.replace(/\.js$/u, ".mjs")}`, + default: mjsPath, }, ]; }),