Skip to content

fix(cjs): keep CommonJS named exports in export * of a dynamically imported module - #11835

Merged
hyfdev merged 5 commits into
mainfrom
fix/11171-literal-cjs-exports
Nov 25, 2026
Merged

hyfdev merged 5 commits into
mainfrom
fix/11171-literal-cjs-exports

Conversation

@hyfdev

@hyfdev hyfdev commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

When a module that is loaded only through import() re-exports a CommonJS module with export *, the namespace that import() returns has none of the CommonJS module's names.

// cjs.cjs
exports.foo = function foo() {};

// re.js
export * from './cjs.cjs';

// entry.js
const ns = await import('./re.js');
console.log('keys:', Object.keys(ns), 'foo:', typeof ns.foo);

Running the source with Node prints keys: [ 'foo', 'module.exports' ] foo: function.

Bundled with --format esm --platform node, the output from main prints keys: [] foo: undefined.

With this PR, it prints keys: [ 'foo' ] foo: function.

Rolldown now collects the names that the CommonJS module assigns with exports.foo = ... or module.exports.foo = ..., and exports them from the module that is loaded only through import().

Each of these exports reads the property of the same name on the CommonJS exports object.

If the object does not have that property itself, for example when it only inherits it, the export is undefined, as in Node.

This applies when:

  • the output format is ESM, code splitting is on, and the build uses neither manual groups (even one that matches no module) nor preserveModules;
  • the module is loaded only through import(), and no module imports it statically;
  • its only export * targets a CommonJS module in the bundle;
  • that CommonJS module is not an entry, and no other module imports or requires it.

@effect/platform-node loads undici this way: with undici 7.30.1, new Agent() works with this PR and fails on main because Agent is undefined.

Other bundlers on the example above:

  • webpack 5.112.2 prints the same as this PR.
  • Rollup 4.68.2 with @rollup/plugin-commonjs 29.0.3 prints the same as main.
  • esbuild 0.28.2 prints the same as main.

Cases this PR does not cover (the output is the same as on main, but Node exposes the names):

  • Names that Node finds in other patterns: Object.defineProperty(exports, 'foo', { get }), module.exports = require('./inner.cjs'), the 0 && (module.exports = { foo }) annotation that esbuild emits, and exports as a UMD factory parameter.
  • Keys other than the assigned names: Node also exposes module.exports, and __esModule when it is set, but this PR does not add them.
  • A CommonJS module that is an entry or that another module imports or requires: other code can change its exports after Node reads them and before the bundle does.

With this PR, two cases still differ from Node:

main has the same difference in both cases with export { foo } from './cjs.cjs' in place of export *.

Closes #11171.

With ESM output, code splitting enabled, preserveModules disabled, and no manual groups, an entry reached only through import() exposes names from direct literal property assignments when its sole resolved export star targets an internal CommonJS module.

Name detection is independent of property inlining. Star re-exports skip default and preserve explicit exports. Each synthesized binding reads an own property of the CommonJS exports and has the value undefined when that property is absent.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

@netlify

netlify Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit 9ad8bb1
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6b066e5b669ed05393267690
😎 Deploy Preview https://deploy-preview-11835--rolldown-rs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@hyfdev
hyfdev marked this pull request as ready for review November 20, 2026 10:36
Copilot AI balanced review requested due to automatic review settings November 20, 2026 10:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@codspeed

codspeed Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 4 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing fix/11171-literal-cjs-exports (9ad8bb1) with main (2ce7ba3)

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@IWANABETHATGUY IWANABETHATGUY self-assigned this Nov 24, 2026
@IWANABETHATGUY

Copy link
Copy Markdown
Member
  • A throwing getter on a synthesized CommonJS export rejects import() even when the caller discards the namespace. Node catches the getter exception and lets the import resolve. Node.js loader

    Reproduction
    // cjs.cjs
    exports.foo = 0;
    Reflect.defineProperty(exports, 'foo', {
      get() { throw new Error('getter failed'); }
    });
    
    // re.mjs
    export * from './cjs.cjs';
    
    // entry.mjs
    await import('./re.mjs');
    console.log('resolved');

    Use Node.js v24.22.3 and the Rolldown CLI built from 557a1d4f4d.

    node entry.mjs
    rolldown entry.mjs -d out -f esm -p node \
      --entryFileNames '[name].mjs' --chunkFileNames '[name]-[hash].mjs'
    node out/entry.mjs

    The source and the bundle from main print resolved. The PR bundle exits with Error: getter failed.

  • When the re-exporting module changes CommonJS then from 0 to a function, the bundled import() calls that function and resolves to a string. Node captures then before the assignment, so the import resolves to the namespace.

    Reproduction
    // cjs.cjs
    exports.then = 0;
    
    // re.mjs
    import cjs from './cjs.cjs';
    export * from './cjs.cjs';
    cjs.then = (resolve) => resolve('assimilated');
    
    // entry.mjs
    const ns = await import('./re.mjs');
    console.log(typeof ns === 'object' ? 'namespace' : ns);

    Use Node.js v24.22.3 and the Rolldown CLI built from 557a1d4f4d.

    node entry.mjs
    rolldown entry.mjs -d out -f esm -p node \
      --entryFileNames '[name].mjs' --chunkFileNames '[name]-[hash].mjs'
    node out/entry.mjs

    The source and the bundle from main print namespace. The PR bundle prints assimilated.

I think we can fix the throwing getter in a follow-up. We should fix the timing issue in this PR because a late read can affect any synthesized CommonJS export.

Node reads the named exports of a CommonJS module when an `import` first loads it. The exports synthesized for a CommonJS star export were read at the end of the chunk, after the re-exporting module's body, so a value that module changed, such as `then`, reached the namespace. Read them in the same statement as the `require` call.

Other code can still change the exports between Node's read and that `require` when the CommonJS module is an entry or has another importer, so synthesize the names only when the re-exporting module is its only importer. Strict mode code cannot declare `eval` or `arguments`, so their bindings get another name.
@hyfdev

hyfdev commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

I'll fix the throwing getter in a follow-up PR.

Your then reproduction now prints namespace, as in Node.

  • The synthesized exports now read the CommonJS values in the same statement as the require call.
  • Names are now synthesized only when the CommonJS module is not an entry and no other module imports or requires it.
  • New fixtures cover the late write and each case that keeps the main output.

Two cases still differ from Node:

  • When a module imported after the export * is in another chunk or is external, it runs before the CommonJS module. That is the default execution order across chunks, and [Bug]: incorrect execution order of static external import #3143 covers externals.
  • The re-exporting module also imports the CommonJS module in an earlier statement. A module that it imports after that statement changes the exports through a global variable. The bundle reads the changed value, and Node reads the value from before the change.

main has the same difference in both cases with export { then } from './cjs.cjs' in place of export *.

I'd fix the second case for both forms in a separate PR.

@IWANABETHATGUY

Copy link
Copy Markdown
Member
  • Sorting the detected CommonJS export names makes the bundle read foo before then. In this repro, the foo getter makes then callable, so import() resolves to a string. Node reads then first, so the import resolves to the namespace. Export name sort

    Reproduction
    // cjs.cjs
    exports.then = 0;
    exports.foo = 0;
    Reflect.defineProperty(exports, 'foo', {
      get() {
        exports.then = (resolve) => resolve('assimilated');
        return 42;
      }
    });
    
    // re.mjs
    export * from './cjs.cjs';
    
    // entry.mjs
    const ns = await import('./re.mjs');
    console.log(typeof ns === 'object' ? 'namespace' : ns);

    Use Node.js v24.22.3 and the Rolldown CLI built from 4eb251a99d.

    node entry.mjs
    rolldown entry.mjs -d out -f esm -p node \
      --entryFileNames '[name].mjs' --chunkFileNames '[name]-[hash].mjs'
    node out/entry.mjs

    The source and the bundle from main print namespace. The PR bundle prints assimilated.

This is related to the earlier then repro. I think we should preserve discovery order when removing duplicate names in this PR.

Node reads the named exports of a CommonJS module in the order it finds them in the source. Sorting the detected names made the synthesized exports read them in another order, so a getter could run earlier than in Node and change a name that had not been read yet: in the new test, the `foo` getter makes `then` a function, and `import()` resolves to its result instead of the namespace.

Collect the names in an index set, which drops duplicates and keeps the order in which they are found.
@hyfdev

hyfdev commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

The detected names now keep their source order, so the synthesized exports read then before foo.

Your reproduction now prints namespace, as in Node.

The new 11171_cjs_star_read_order fixture covers it.

@hyfdev
hyfdev merged commit c5d9a49 into main Nov 25, 2026
37 checks passed
@hyfdev
hyfdev deleted the fix/11171-literal-cjs-exports branch November 25, 2026 05:21
@rolldown-guard rolldown-guard Bot mentioned this pull request Nov 26, 2026
shulaoda added a commit that referenced this pull request Nov 26, 2026
## [1.3.4] - 2026-11-26

### 🚀 Features

- add builtin `injectPlugin` with `include`/`exclude` (#11290) by @onmax
- magic-string: support explicit sourcemap locations (#11884) by @IWANABETHATGUY
- introduce `declaredModuleSize` to allow plugins to declare a module's real size (#11844) by @hyfdev
- binding: add dropInner() to 12 binding classes and extract release_arc helper (#11855) by @Brooooooklyn
- inline-common-chunks: add `maxDuplicatedSize` to keep widely copied chunks as files (#11845) by @mattlewis92
- cli: report when a watch round finishes (#11820) by @hyfdev
- rolldown_plugin_vite_build_import_analysis: avoid stripping import attributes when `experimental.importAttributes` is enabled (#11802) by @sapphi-red
- import-attributes: warn when a non-ESM output drops the import attributes of an external (#11797) by @shulaoda
- warn when the `watch` option is passed to `build()` (#11781) by @shulaoda

### 🐛 Bug Fixes

- keep_names: restore hoisted function names before the chunk's modules run (#11962) by @hyfdev
- external: don't drop `_/` from relative external imports (#11968) by @hyfdev
- external: don't panic on empty output filename with relative externals (#11963) by @hyfdev
- use the same path as direct imports for externals re-exported with `export *` (#11964) by @hyfdev
- sourcemap: don't panic on empty output filename (#11966) by @hyfdev
- sourcemap: treat empty `sourcemapFileNames` as unset (#11967) by @hyfdev
- rename clashing names in execution order with `chunkModulesOrder: 'module-id'` (#11943) by @hyfdev
- code-splitting: stop counting JSON modules as 0 bytes (#11939) by @hyfdev
- fetch changed modules from their creating resolution in incremental rebuilds (#11837) by @h-a-n-a
- code-splitting: keep import order through entry re-exports (#11906) by @hyfdev
- cjs: keep CommonJS named exports in `export *` of a dynamically imported module (#11835) by @hyfdev
- plugin: remove internal keys from plugin and code splitting group contexts (#11914) by @hyfdev
- remove the leftover `watch.notify` from the option validator (#11918) by @shulaoda
- return the group chunk file from `getFileName()` for a merged emitted entry (#11858) by @IWANABETHATGUY
- dev: let `this.load` of an unchanged module finish during a rebuild (#11911) by @hyfdev
- code-splitting: avoid an extra shared chunk when an entry only re-exports another entry (#11847) by @hyfdev
- treeshake: remove unused objects containing identity function calls (#11852) by @hyfdev
- cjs: avoid `ReferenceError` when re-exporting from an external `export *` in another chunk (#11848) by @hyfdev
- binding: remove stale WASI workaround in to_binding_error (#11890) by @Brooooooklyn
- inline-const: respect `inlineConst` options for default exports (#11851) by @hyfdev
- magic-string: keep trailing lines in decoded maps (#11882) by @IWANABETHATGUY
- magic-string: preserve column mappings through trim (#11881) by @IWANABETHATGUY
- magic-string: map each line of multiline replacements (#11880) by @IWANABETHATGUY
- follow Rollup for module meta and moduleSideEffects set by plugins (#11792) by @h-a-n-a
- code-splitting: import the bindings a CommonJS entry re-exports from an ES module (#11839) by @hyfdev
- cjs: stop overwriting `module.exports` of a CommonJS entry that re-exports an ES module (#11846) by @hyfdev
- sourcemap: accept undefined source entries from plugins (#11850) by @fengmk2
- code-splitting: unblock top-level awaited dynamic imports in manual groups (#11819) by @hyfdev
- runtime: resolve `require()` from the calling chunk in Node ESM output (#11834) by @hyfdev
- plugin: throw instead of panicking when a saved transform context calls `getCombinedSourcemap` (#11838) by @hyfdev
- code-splitting: only code-less entries keep side-effect-free static import edges (#11199) by @mattlewis92
- make `getCombinedSourcemap` work with `experimental.nativeMagicString` (#11107) by @IWANABETHATGUY
- plugin: avoid hangs when resolveId awaits this.load() (#11824) by @shulaoda
- keep template chunk names from overwriting explicit file names (#11831) by @hyfdev
- code-splitting: skip redundant re-export chunks (#11817) by @hyfdev
- preserve build errors when `buildEnd` fails (#11828) by @sapphi-red
- preserve top-level using with topLevelVar (#11804) by @akshathayadav378-boop
- treeshake: keep array destructuring that calls an unknown iterator (#11812) by @IWANABETHATGUY
- preserve `export` names starting with `*` in ModuleInfo.exports (#11825) by @sapphi-red
- treeshake: keep calls to functions that direct `eval` can replace (#11811) by @IWANABETHATGUY
- keep each source's content in a multi-source transform sourcemap (#11246) by @IWANABETHATGUY
- treeshake: keep calls to empty functions with a rest parameter default (#11810) by @IWANABETHATGUY
- plugin: allow this.load() while resolving entries (#11816) by @hyfdev
- cli: avoid a WASI hang when watch mode exits normally (#11815) by @shulaoda
- report effective moduleSideEffects in getModuleInfo and this.resolve (#11422) by @cestercian
- code-splitting: avoid an import cycle through an entry's re-exports (#11803) by @hyfdev
- treeshake: apply @__NO_SIDE_EFFECTS__ to functions exported after declaration (#11222) by @araishi
- code-splitting: keep unused entry re-exports from loading lazy chunks (#11753) by @hyfdev
- code-splitting: keep re-exported bindings out of dynamic import namespaces (#11799) by @hyfdev
- perf-kit: Node mode times out under the inspector with `--ready exit` or an anchored `stdout:` pattern (#11416) by @IWANABETHATGUY
- treeshaking: drop dead dynamic imports that form a cycle (#11768) by @hyfdev
- binding: release the WASI runtime when a callable builtin plugin hook rejects (#11786) by @shulaoda
- perf-kit: print real imports in the why chain (#11500) by @IWANABETHATGUY
- chunk: name emitted chunks before shared chunks (#11790) by @hyfdev
- cjs: forward exports from duplicate CommonJS entries (#11756) by @hyfdev
- code-splitting: keep chained emitted entries from becoming empty facades (#11090) by @Huzaifa-Asif

### 💼 Other

- wasi: bundle self-contained WASI loaders, staging script, and reactor checks (#11843) by @Brooooooklyn

### 🚜 Refactor

- scan: remove an unreachable branch when collecting dynamic import entries (#11919) by @shulaoda
- cli: replace the unreachable prototype pollution guard with a test (#11925) by @shulaoda
- remove the unused `DeterminedSideEffects::to_module_side_effects` (#11926) by @shulaoda
- remove more unused types, functions and re-exports (#11922) by @shulaoda
- link_stage: handle required modules only in the pre-pass (#11920) by @shulaoda
- cli: remove the leftover `inject` from the CLI options type (#11924) by @shulaoda
- rolldown_plugin_vite_build_import_analysis: remove the unused `optimizeModulePreloadRelativePaths` option (#11923) by @shulaoda
- remove experimental `freeExternalMemory` (#11886) by @shulaoda
- rust: drop direct tokio dependencies from core library crates (#11841) by @Brooooooklyn
- rolldown_plugin: move `normalize_transform_sourcemap` to utils (#11247) by @IWANABETHATGUY
- remove the unused `plugins_are_slow` method (#11800) by @shulaoda
- remove parallel plugin support (#11789) by @h-a-n-a
- remove the unused `is_css` sourcemap flag (#11782) by @shulaoda

### 📚 Documentation

- rename javascript to JavaScript (#11958) by @mdong1909
- say that resolveId fails the build when the same id is external and not external (#11910) by @h-a-n-a
- explain which resolution sets meta and moduleSideEffects in resolveId (#11907) by @h-a-n-a
- resolve the import in the `moduleSideEffects` plugin example (#11860) by @hyfdev
- clarify side-effect-free module behavior (#11856) by @IWANABETHATGUY
- clarify the behavior when `buildEnd` / `renderError` itself errors (#11829) by @sapphi-red
- add docs for `code` / `plugin` / `pluginCode` of `RolldownLog` (#11827) by @sapphi-red
- explain that a module in an entry chunk runs after the common chunks it imports (#11822) by @hyfdev
- magic-string: document `generateDecodedMap` and the segments of `hires: false` maps (#11791) by @IWANABETHATGUY

### ⚡ Performance

- binding: return memory to the OS once rolldown is idle (#11655) by @shulaoda
- scan: reserve symbol capacity for each module's facade symbols (#11854) by @magurotuna
- runtime: stop using bound functions as `__copyProps` getters (#11826) by @magurotuna
- replace `IndexVec<ModuleIdx, bool>` with `IndexBitSet` (#11805) by @IWANABETHATGUY
- rolldown_plugin_vite_manifest: look up chunk names by file name once per build (#11697) by @Boshen
- drop module sourcemaps after the chunk is joined (#11773) by @shulaoda

### 🧪 Testing

- magic-string: re-enable two passing compatibility tests (#11879) by @IWANABETHATGUY
- node: add standalone runtime/proxy/retained-context tests and vitest binding staging (#11842) by @Brooooooklyn
- cli: stop watch CLI tests from hanging on Windows (#11821) by @shulaoda

### ⚙️ Miscellaneous Tasks

- delete cancelled pkg.pr.new runs on main and debounce for 15 mins (#11928) by @shulaoda
- remove the unused `serde` features of rolldown, rolldown_plugin and rolldown_common (#11927) by @shulaoda
- deps: update vite-plus to v1.8.0 in the workspace and CI (#11896) by @camc314
- deps: update rollup submodule for tests to v4.68.8 (#11901) by @rolldown-guard[bot]
- deps: update test262 submodule for tests (#11902) by @rolldown-guard[bot]
- remove the graphite merge-when-ready label check (#11904) by @shulaoda
- deps: pin walkdir to 2.5.0 (#11897) by @hyfdev
- deps: remove remove-unused-vars (#11895) by @camc314
- deps: update rust crate testing_macros to v3 (#11876) by @renovate[bot]
- deps: update rust crates (#11873) by @renovate[bot]
- deps: update npm packages (#11872) by @renovate[bot]
- deps: upgrade oxc to 0.160.0 (#11885) by @camc314
- deps: update github actions (#11874) by @renovate[bot]
- rust: standalone runtime prep (devtools sync writer, TestDir, 1ms debounce, Wasm sourcemap inline, parking_lot_core patch) (#11840) by @Brooooooklyn
- run setup steps one by one on Windows (#11849) by @shulaoda

### ◀️ Revert

- "feat(binding): add dropInner() to 12 binding classes and extract release_arc helper (#11855)" (#11898) by @shulaoda
- "fix(code-splitting): keep chained emitted entries from becoming empty facades (#11090)" (#11891) by @hyfdev

### ❤️ New Contributors

* @fengmk2 made their first contribution in [#11850](#11850)
* @akshathayadav378-boop made their first contribution in [#11804](#11804)
* @araishi made their first contribution in [#11222](#11222)
* @Huzaifa-Asif made their first contribution in [#11090](#11090)

Co-authored-by: shulaoda <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: export * from a CommonJS module in a dynamically imported chunk loses the named exports

3 participants