From c797aadfc06990c9221bba0dd74aba90ead42c08 Mon Sep 17 00:00:00 2001 From: Momena <152077758+Momena-akhtar@users.noreply.github.com> Date: Mon, 14 Jul 2025 12:47:12 +0500 Subject: [PATCH] doc: add guide for runtime-specific conditional exports using --import --- .../runtime-conditional-exports.md | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 doc/contributing/runtime-conditional-exports.md diff --git a/doc/contributing/runtime-conditional-exports.md b/doc/contributing/runtime-conditional-exports.md new file mode 100644 index 00000000000000..fbcaf93372268c --- /dev/null +++ b/doc/contributing/runtime-conditional-exports.md @@ -0,0 +1,39 @@ +# Runtime-Specific Conditional Exports in Node.js + +Node.js supports conditional exports based on environments such as `"node"`, `"browser"`, and `"import"`. However, runtime-specific conditions like `"electron"` are not included by default and **currently cannot be added dynamically** to the module resolution process. + +This guide demonstrates how to simulate runtime-specific behavior without modifying Node.js core. + +## Example: Supporting `"electron"` as a Condition + +You can use the `--import` flag to preload a script that sets runtime-specific flags. + +### Step 1: Preload Script + +```js +// register-conditions.js +if (process.versions.electron) { + process.env.EXPORTS_CONDITION = 'electron'; +} +``` +### Step 2: Application Code + +```js +// index.js +if (process.env.EXPORTS_CONDITION === 'electron') { + module.exports = require('./electron-specific.js'); +} else { + module.exports = require('./default.js'); +} +``` +### Step 3: Run with Preload + +```bash +node --import ./register-conditions.js index.js +``` + +### Notes + +- This technique does not affect the `exports` field resolution in `package.json`, but allows dynamic control within your application. +- For advanced usage with ESM resolution, consider using a custom loader. +