Skip to content

Support named exports with nodejs ESM#5162

Open
robrichard wants to merge 1 commit intofacebook:mainfrom
robrichard:robrichard/cjs-named-exports
Open

Support named exports with nodejs ESM#5162
robrichard wants to merge 1 commit intofacebook:mainfrom
robrichard:robrichard/cjs-named-exports

Conversation

@robrichard
Copy link
Contributor

It is currently not possible to use named exports with Relay in a Node.js ESM file. For example, in a brand new project with the latest version of relay-runtime as a dependency, the following code will error:

index.mjs:

import { fetchQuery } from 'relay-runtime'
file:///index.mjs:1
import { fetchQuery } from 'relay-runtime';
         ^^^^^^^^^^
SyntaxError: Named export 'fetchQuery' not found. The requested module 'relay-runtime' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'relay-runtime';
const { fetchQuery } = pkg;

    at #asyncInstantiate (node:internal/modules/esm/module_job:302:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:405:5)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:660:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)

When an ESM file imports a common js file (like relay-runtime) Node.js will use cjs-module-lexer to try to determine compatible named exports.

From the node.js docs:

Named exports detection covers many common export patterns, reexport patterns and build tool and transpiler outputs. See cjs-module-lexer for the exact semantics implemented.

In the entry points of react-relay and relay-runtime, the pattern of exporting a property on another object causes cjs-module-lexer to not detect any of named exports.

Example:

// This doesn't work
module.exports = {
  fetchQuery: RelayRuntime.fetchQuery
};

// This does work
const { fetchQuery } = RelayRuntime;
module.exports = {
  fetchQuery
};

In this PR, I updated the entrypoints of react-relay and relay-runtime to allow Node.js's cjs named export detection to work properly. I added a test case to the Gulp build process since to test this we need the final transpiled code, but I am open to other approaches.

@meta-cla meta-cla bot added the CLA Signed label Feb 5, 2026
@robrichard robrichard force-pushed the robrichard/cjs-named-exports branch from 9828617 to 28d1934 Compare February 12, 2026 14:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant