Skip to content

doc: guide for runtime-specific conditional exports using --import #59066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions doc/contributing/runtime-conditional-exports.md
Original file line number Diff line number Diff line change
@@ -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.