Skip to content

Comments

fix: missing CJS default export when SafelyMergeCjsNs optimization is enabled#7006

Merged
sapphi-red merged 6 commits intomainfrom
copilot/fix-cjs-default-export-issue
Nov 15, 2025
Merged

fix: missing CJS default export when SafelyMergeCjsNs optimization is enabled#7006
sapphi-red merged 6 commits intomainfrom
copilot/fix-cjs-default-export-issue

Conversation

Copy link
Contributor

Copilot AI commented Nov 14, 2025

Fix missing CJS default export when SafelyMergeCjsNs optimization is enabled

Issue: When a CJS module is imported with both named and default imports, and the SafelyMergeCjsNs optimization is applied (enabled for react, react/jsx-runtime, and test modules), the __toESM helper was not generated, causing the default export to be undefined.

Changes

  • crates/rolldown/src/module_finalizers/mod.rs: Always use __toESM when SafelyMergeCjsNs flag is set, regardless of import_record_needs_interop result
  • Moved test cases from bundler_esm_cjs_tests/65,66 to cjs_compat/module.exports_export/ with descriptive names:
    • safely_merge_cjs_ns_with_default_import: Tests combined default and named imports in a single statement
    • safely_merge_cjs_ns_with_separate_imports: Tests separate import statements for default and named imports
  • Updated test cases to use proper assertions with assert.deepStrictEqual

Example

Before (broken):

import React from 'react';
import { useState } from 'react';

console.log(React);  // undefined when namespace is merged

After (fixed):

var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
console.log(import_react.default);  // Function

The fix ensures CJS namespace merging preserves default export semantics by generating proper interop code.

Original prompt

This section details on the original issue you should resolve

<issue_title>[Bug]: CJS default export is missing when the same module is imported with named imports and default imports</issue_title>
<issue_description>### Reproduction link or steps

https://stackblitz.com/edit/p5a3vok2?file=rolldown.config.ts,index.mjs,dist%2Findex.js,react.cjs

What is expected?

[Function (anonymous)] { ...omit... } to be output when running node dist/index.js.
In other words, dist/index.js to contain var import_react = /* @__PURE__ */ __toESM(require_react(), 1);

What is actually happening?

[Function (anonymous)] undefined is output when running node dist/index.js.
In other words, dist/index.js contains var import_react = require_react();.

System Info

StackBlitz

  System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 20.19.1 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.8.2 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @rolldown/browser:  1.0.0-beta.50

Any additional comments?

Probably related to #6850</issue_description>

<agent_instructions>This is related to ImportRecordMeta::SafelyMergeCjsNs optimization. Always use __toESM if ImportRecordMeta::SafelyMergeCjsNs optimization is used.

if rec.meta.contains(ImportRecordMeta::SafelyMergeCjsNs) {
let chunk_idx = self.ctx.chunk_id;
if let Some(symbol_ref_to_be_merged) =
self.ctx.chunk_graph.finalized_cjs_ns_map_idx_vec[chunk_idx].get(&rec.namespace_ref)
{
if symbol_ref_to_be_merged != &rec.namespace_ref {
return true;
}
}
}
</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@sapphi-red [REPL](https://repl.rolldown.rs/#eNp9jkEKwjAQRa8SZlOFmqaCC1u8hOuA1HYqlSYjSVoKJXc3sRXFhcs/8/j/zdBCMUOnG5y4utsYNBRfhxTqmNWDjGMzG9HYjjTzrDWkWGKwql1SSr0S55h/f1LXpC31yHu6bdaKdGG34R9GEApnBvQpaGrwoqgZerTZqyJbbD52/5DFF6doY/lb98Qk5Ee+50JCKU2Y9GFqDGTOBRe7K7qKHwT4JxYQW3c=)

💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

@graphite-app
Copy link
Contributor

graphite-app bot commented Nov 14, 2025

How to use the Graphite Merge Queue

Add the label graphite: merge to this PR to add it to the merge queue.

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

@netlify
Copy link

netlify bot commented Nov 14, 2025

Deploy Preview for rolldown-rs canceled.

Name Link
🔨 Latest commit 5d656f3
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/69182f3b75682a0008cb03a1

Copilot AI changed the title [WIP] Fix missing CJS default export when using named imports Fix missing CJS default export when SafelyMergeCjsNs optimization is enabled Nov 14, 2025
Copilot AI requested a review from sapphi-red November 14, 2025 09:39
@sapphi-red
Copy link
Member

@copilot move the tests under crates/rolldown/tests/rolldown/cjs_compat/module.exports_export and name it descriptively

Copy link
Contributor Author

Copilot AI commented Nov 14, 2025

@copilot move the tests under crates/rolldown/tests/rolldown/cjs_compat/module.exports_export and name it descriptively

Done. Moved tests to:

  • cjs_compat/module.exports_export/safely_merge_cjs_ns_with_default_import/ (combined default and named imports)
  • cjs_compat/module.exports_export/safely_merge_cjs_ns_with_separate_imports/ (separate import statements)

Commit: 7e5eb1a

Copilot AI requested a review from sapphi-red November 14, 2025 10:09
@sapphi-red sapphi-red changed the title Fix missing CJS default export when SafelyMergeCjsNs optimization is enabled fix: missing CJS default export when SafelyMergeCjsNs optimization is enabled Nov 14, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Nov 14, 2025

Benchmarks Rust

  • target: main(c5fb93f)
  • pr: copilot/fix-cjs-default-export-issue(5d656f3)
group                                                        pr                                     target
-----                                                        --                                     ------
bundle/bundle@multi-duplicated-top-level-symbol              1.03     67.6±2.30ms        ? ?/sec    1.00     65.9±2.26ms        ? ?/sec
bundle/bundle@multi-duplicated-top-level-symbol-sourcemap    1.02     74.9±2.00ms        ? ?/sec    1.00     73.5±3.08ms        ? ?/sec
bundle/bundle@rome_ts                                        1.02    109.3±2.04ms        ? ?/sec    1.00    106.9±1.75ms        ? ?/sec
bundle/bundle@rome_ts-sourcemap                              1.02    123.1±1.83ms        ? ?/sec    1.00    120.2±1.71ms        ? ?/sec
bundle/bundle@threejs                                        1.02     40.3±1.31ms        ? ?/sec    1.00     39.7±2.34ms        ? ?/sec
bundle/bundle@threejs-sourcemap                              1.04     44.3±1.13ms        ? ?/sec    1.00     42.7±1.09ms        ? ?/sec
bundle/bundle@threejs10x                                     1.01    400.6±4.80ms        ? ?/sec    1.00    397.8±6.22ms        ? ?/sec
bundle/bundle@threejs10x-sourcemap                           1.01    459.2±3.10ms        ? ?/sec    1.00    455.7±6.46ms        ? ?/sec
scan/scan@rome_ts                                            1.00     85.9±1.69ms        ? ?/sec    1.03     88.0±2.67ms        ? ?/sec
scan/scan@threejs                                            1.00     28.7±0.45ms        ? ?/sec    1.01     28.9±0.48ms        ? ?/sec
scan/scan@threejs10x                                         1.00    301.0±4.04ms        ? ?/sec    1.01    302.8±5.42ms        ? ?/sec

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a bug where CJS default exports were missing when the SafelyMergeCjsNs optimization is enabled (for modules like react and react/jsx-runtime). The issue occurred when a CJS module was imported with both named and default imports, and the __toESM helper was not being generated, causing the default export to be undefined.

Key changes:

  • Modified the condition in module_finalizers/mod.rs to always use __toESM when SafelyMergeCjsNs flag is set
  • Added two comprehensive test cases demonstrating both combined and separate import statement scenarios
  • Tests use proper assertions with assert.deepStrictEqual and verify that __toESM is correctly generated in the output

Reviewed Changes

Copilot reviewed 8 out of 12 changed files in this pull request and generated no comments.

File Description
crates/rolldown/src/module_finalizers/mod.rs Core fix: Added check for SafelyMergeCjsNs flag to ensure __toESM helper is always generated when namespace merging is enabled
crates/rolldown/tests/rolldown/cjs_compat/module.exports_export/safely_merge_cjs_ns_with_default_import/* Test case for combined default and named imports in a single statement
crates/rolldown/tests/rolldown/cjs_compat/module.exports_export/safely_merge_cjs_ns_with_separate_imports/* Test case for separate import statements for default and named imports
crates/rolldown/tests/snapshots/integration_rolldown__filename_with_hash.snap Updated snapshot to include new test case hash entries

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@IWANABETHATGUY
Copy link
Member

IWANABETHATGUY commented Nov 14, 2025

image Even if I revert the modification in the Rust side, the test still passes. image

@sapphi-red
Copy link
Member

@IWANABETHATGUY Good catch! The import order was swapped from the reproduction I had. I've fixed that and confirmed that the test fails without the change now.

@IWANABETHATGUY IWANABETHATGUY force-pushed the copilot/fix-cjs-default-export-issue branch from e910ecf to 61af396 Compare November 15, 2025 05:16
@sapphi-red sapphi-red force-pushed the copilot/fix-cjs-default-export-issue branch from 61af396 to 5d656f3 Compare November 15, 2025 07:43
@sapphi-red sapphi-red enabled auto-merge (squash) November 15, 2025 07:55
@sapphi-red sapphi-red merged commit 081ac9b into main Nov 15, 2025
28 checks passed
@sapphi-red sapphi-red deleted the copilot/fix-cjs-default-export-issue branch November 15, 2025 07:57
graphite-app bot pushed a commit that referenced this pull request Nov 17, 2025
…mports are used from a CJS module (#7094)

`canonical name not found for "__toESM"` error when only named imports are used from a CJS module and SafelyMergeCjsNs optimization is applied.

refs #7006, #6850
sapphi-red added a commit that referenced this pull request Nov 18, 2025
…mports are used from a CJS module (#7094)

`canonical name not found for "__toESM"` error when only named imports are used from a CJS module and SafelyMergeCjsNs optimization is applied.

refs #7006, #6850
This was referenced Nov 19, 2025
shulaoda added a commit that referenced this pull request Nov 19, 2025
## [1.0.0-beta.51] - 2025-11-19

### 💥 BREAKING CHANGES

- rolldown_plugin_vite_react_refresh_wrapper: add vite prefix (#7086) by
@shulaoda
- rolldown_plugin_vite_web_worker_post: add vite prefix (#7085) by
@shulaoda
- rolldown_plugin_vite_wasm_helper: add vite prefix (#7084) by @shulaoda
- rolldown_plugin_vite_wasm_fallback: add vite prefix (#7083) by
@shulaoda
- rolldown_plugin_vite_transform: add vite prefix (#7082) by @shulaoda
- rolldown_plugin_vite_reporter: add vite prefix (#7081) by @shulaoda
- rolldown_plugin_vite_module_preload_polyfill: add vite prefix (#7080)
by @shulaoda
- rolldown_plugin_vite_manifest: add vite prefix (#7079) by @shulaoda
- rolldown_plugin_vite_load_fallback: add vite prefix (#7072) by
@shulaoda
- rolldown_plugin_vite_json: add vite prefix (#7071) by @shulaoda
- rolldown_plugin_vite_import_glob: add vite prefix (#7070) by @shulaoda
- rolldown_plugin_vite_html_inline_proxy: add vite prefix (#7069) by
@shulaoda
- rolldown_plugin_vite_dynamic_import_vars: add vite prefix (#7068) by
@shulaoda
- rolldown_plugin_vite_build_import_analysis: add vite prefix (#7067) by
@shulaoda
- rolldown_plugin_vite_asset_import_meta_url: add vite prefix (#7066) by
@shulaoda
- rolldown_plugin_vite_alias: add vite prefix (#7065) by @shulaoda
- rolldown_plugin_vite_asset_plugin: add vite prefix (#7064) by
@shulaoda

### 🚀 Features

- export sync APIs to experimental (#7122) by @shulaoda
- rolldown_plugin_vite_asset_import_meta_url: implement template literal
support for dynamic URLs (#7118) by @shulaoda
- rolldown_plugin_vite_asset_import_meta_url: implement AST-based URL
detection (#7113) by @shulaoda
- add isPathFragment validation for filename patterns (rollup compat)
(#7101) by @IWANABETHATGUY
- rolldown_plugin_vite_asset_import_meta_url: align filter logic (#7103)
by @shulaoda
- rolldown: oxc v0.98.0 (#6961) by @camc314
- show error contexts for unhandleable errors (#7095) by @sapphi-red
- rolldown_plugin_utils: extract `get_hash` utility function (#7059) by
@shulaoda
- rolldown_plugin_asset: initialize `CSSEntriesCache` (#7015) by
@shulaoda
- rolldown_plugin_vite_html: align `transformIndexHtml` logic (#7010) by
@shulaoda
- builtin-plugin: support `bindingifyViteHtmlPlugin` (#7008) by
@shulaoda
- impl `generatedCode.symbols` for reexport dynamic modules. (#6993) by
@IWANABETHATGUY
- rolldown_plugin_manifest: support v2 logic (#6979) by @shulaoda
- support Node.js `module.exports` ESM export (#6967) by @Copilot
- change "could not clean directory" from error to warning (#6955) by
@Copilot
- rolldown_binding: add context to errors thrown by plugin hooks (#6964)
by @sapphi-red

### 🐛 Bug Fixes

- content hash should be affected by the minify behavior (#7102) by
@hyf0
- `canonical name not found for "__toESM"` error when only named imports
are used from a CJS module (#7094) by @sapphi-red
- preserve directory structure in chunk names with preserveModules
(#6872) by @IWANABETHATGUY
- rolldown_plugin_asset: correct bundle deletion index calculation
(#7063) by @shulaoda
- rolldown_plugin_utils: correct string slicing in
`render_asset_url_in_js` (#7061) by @shulaoda
- rolldown_plugin_vite_html: use transformed result in asset URL
handling (#7060) by @shulaoda
- rolldown_plugin_vite_html: skip redundant path resolution for
processed URLs (#7058) by @shulaoda
- rolldown_plugin_vite_css_post: data race in CSS URL processing (#7055)
by @shulaoda
- rolldown_plugin_vite_css_post: always compute css asset dirname in
build command (#7054) by @shulaoda
- rolldown_plugin_vite_css: ensure consistent url in import and export
(#7053) by @shulaoda
- rolldown_plugin_vite_css_post: use `get_or_insert_default` for
`HTMLProxyResult` (#7052) by @shulaoda
- rolldown_plugin_vite_css: skip `commonjs-proxy` CSS requests (#7050)
by @shulaoda
- rolldown_plugin_utils: correct `is_css_module` (#7049) by @shulaoda
- rolldown_plugin_utils: correct `is_css_request` (#7048) by @shulaoda
- rolldown_plugin_vite_html: use correct inline module index (#7046) by
@shulaoda
- rolldown_plugin_vite_html: correct scripts url update logic (#7045) by
@shulaoda
- rolldown_plugin_vite_html: fallback to original url on NotFound error
(#7043) by @shulaoda
- rolldown_plugin_vite_html: move src_tasks to correct branch (#7040) by
@shulaoda
- rolldown_plugin_vite_html: correct `handle_style_tag_or_attribute`
(#7038) by @shulaoda
- builtin-plugin: add `config` to `htmlInlineProxyPlugin` (#7036) by
@shulaoda
- missing CJS default export when SafelyMergeCjsNs optimization is
enabled (#7006) by @Copilot
- reserve global names before deconflicting external symbols (#7022) by
@IWANABETHATGUY
- rolldown_plugin_build_import_analysis: process all bundle outputs
correctly (#7020) by @shulaoda
- rolldown_plugin_vite_css_post: process all bundle outputs correctly
(#7019) by @shulaoda
- rolldown_plugin_vite_css_post: remove `/*$vite$:1*/` correctly (#7018)
by @shulaoda
- rolldown_plugin_vite_html: use correct span for `style_urls` (#7017)
by @shulaoda
- rolldown_plugin_vite_html: track full element span from start to end
tag (#7016) by @shulaoda
- builtin-plugin: correct `viteHtmlPlugin` related logic (#7013) by
@shulaoda
- remove unused module namespace object exporting (#7002) by
@IWANABETHATGUY
- rust/dev: allow to recover from hmr rebuild failure (#6991) by @hyf0
- rust/dev: `ensure_latest_bundle_output` shouldn't loop infinitely
(#6974) by @hyf0
- rust/dev: `DevEngine#ensure_latest_bundle_output` should schedule a
rebuild task if there're no queued tasks (#6968) by @hyf0
- add Symbol.toStringTag to module facades when generatedCode.symbols is
enabled (#6784) by @Copilot

### 🚜 Refactor

- extension checking to use constant array (#7057) by @Copilot
- rust/devtools: tweak namings and introduction comments (#7028) by
@hyf0
- rolldown_plugin_vite_html: use `root` instead of `cwd` (#7035) by
@shulaoda
- rolldown_plugin_vite_css_post: use `root` instead of `cwd` (#7034) by
@shulaoda
- rolldown_plugin_vite_css: use `root` instead of `cwd` (#7033) by
@shulaoda
- rolldown_plugin_transform: use `root` instead of `cwd` (#7032) by
@shulaoda
- rolldown_plugin_reporter: use `root` instead of `cwd` (#7031) by
@shulaoda
- rolldown_plugin_asset: use `root` instead of `cwd` (#7030) by
@shulaoda
- rolldown_plugin_html_inline_proxy: use `root` instead of `cwd` (#7029)
by @shulaoda
- rust/dev: remove dead code of `rolldown_dev` crate (#6997) by @hyf0
- rust: move dev related code into new `rolldown_dev` crate (#6996) by
@hyf0
- rolldown_resolver: use consistent generic parameter name `Fs` (#6998)
by @shulaoda
- rolldown_resolver: improve resolve method clarity and documentation
(#6986) by @shulaoda
- rename `is_module_facade()` to `is_entry_point()` for clarity (#6994)
by @IWANABETHATGUY
- rust/dev: unwrap `Result<_>` from the return type of
`BundleCoordinator::schedule_build_if_stale` (#6980) by @sapphi-red
- rolldown_resolver: reorganize impl blocks (#6984) by @shulaoda
- rolldown_resolver: extract configuration logic into separate module
(#6983) by @shulaoda
- rolldown_resolver: improve error messages (#6982) by @shulaoda
- rust/dev: rename `CoordinatorStatus` to `CoordinatorStateSnapshot`
(#6973) by @hyf0
- rust/dev: replace `InitialBuildState` with `CoordinatorState` (#6972)
by @hyf0
- ast_scanner: derive `Debug`, `Clone`, `Copy` for
`CjsGlobalAssignmentType` (#6971) by @camc314
- rust: filter out devtools specific events for normal tracing (#6965)
by @hyf0
- rust/dev: replace `CoordinatorMsg::HasLatestBuildOutput` with
`GetStatus` (#6960) by @hyf0
- rust/dev: `ensure_current_build_finish` shouldn't block the
coordinator's event loop (#6959) by @hyf0

### 📚 Documentation

- in-depth/directives: remove TODOs and fix code (#7112) by @sapphi-red
- clarify concepts of rolldown's test infra (#7047) by @hyf0
- contrib/style: add suggestions about choosing file names (#6989) by
@hyf0

### ⚡ Performance

- rolldown_plugin_vite_css_post: cache CSS URL processing results
(#7056) by @shulaoda
- remove unnecessary `collect_vec` (#6999) by @IWANABETHATGUY

### 🧪 Testing

- add testcase for #6880 and #6879 (#7107) by @IWANABETHATGUY
- vite-tests: use integration branch for vite compatibility tests
(#7091) by @shulaoda

### ⚙️ Miscellaneous Tasks

- remove redundant chunk level linefeed (#7109) by @IWANABETHATGUY
- pin oxc-minify to 0.97.0 (#7108) by @IWANABETHATGUY
- deps: update oxc apps (#7104) by @renovate[bot]
- deps: update glob for security (#7105) by @shulaoda
- rolldown: add aliases for renamed vite plugins (#7087) by @shulaoda
- automate weekly beta releases (#7089) by @Boshen
- deps: update dependency oxlint-tsgolint to v0.7.0 (#7088) by
@renovate[bot]
- deps: update github-actions (#7075) by @renovate[bot]
- deps: update dependency oxlint-tsgolint to v0.6.0 (#7037) by
@renovate[bot]
- deps: update npm packages (#7076) by @renovate[bot]
- deps: update rust crates (#7077) by @renovate[bot]
- add retry to flaky tests (#7041) by @sapphi-red
- rust: rename `rolldown_debug` to `rolldown_devtools` (#7026) by @hyf0
- deps: update crate-ci/typos action to v1.39.2 (#7001) by
@renovate[bot]
- ai/github: make copilot review check rust api style (#6988) by @hyf0
- move test `recover_from_initial_build_error` to
`error_recovery/from_initial_build_syntax_error` (#6990) by @hyf0
- oxlint: enable `typescript/consistent-type-imports` rule (#6987) by
@shulaoda
- deps: update crate-ci/typos action to v1.39.1 (#6975) by
@renovate[bot]
- build.ts: separate import type (#6921) by @iiio2
- format rolldown runtime (#6966) by @IWANABETHATGUY

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]: CJS default export is missing when the same module is imported with named imports and default imports

3 participants