Skip to content

fix: treat top-level this of a required module without module syntax as its exports - #11271

Merged
hyfdev merged 4 commits into
rolldown:mainfrom
sarankumar1325:fix/cjs-this-required-js
Nov 6, 2026
Merged

hyfdev merged 4 commits into
rolldown:mainfrom
sarankumar1325:fix/cjs-this-required-js

Conversation

@sarankumar1325

Copy link
Copy Markdown
Contributor

Closes #11269.

What

A .js file without module syntax (no import/export, no require/module/exports) is scanned as ExportsKind::None, so the scanner maps its top-level this to ThisExprReplaceKind::Context and prints it as void 0. When such a file is only reached through require(), the link stage promotes it to CommonJs and wraps it with __commonJSMin, but its this stays void 0. UMD-style files like (function (global) { ... })(this) then crash with TypeError: Cannot set properties of undefined. Node runs the file as CommonJS, where top-level this is module.exports.

Change

In determine_module_exports_kind, the Require and no-code-splitting DynamicImport arms that promote a None module to CommonJs now call a new promote_to_commonjs. When the module has top-level this, it switches those entries to ThisExprReplaceKind::Exports, sets EcmaModuleAstUsage::ExportsRef and creates cjs_this_ref, as the scanner already does for a module with CommonJS syntax. The finalizer then prints this as the this parameter of the CJS closure:

var require_thing = /* @__PURE__ */ __commonJSMin(((exports, module, this$2) => {
	(function(global) {
		global.Thing = function Thing() {};
	})(this$2);
}));

Modules promoted on other paths (for example a None module imported by an import from a CommonJS module) keep their current behaviour. I also updated internal-docs/linking/determine-module-exports-kind/implementation.md.

Tests

  • New fixture crates/rolldown/tests/rolldown/issues/11269: thing.js (the issue's UMD file) and direct.js (this.direct = ...) are only reached through require(). On main the bundle fails with TypeError: Cannot set properties of undefined (setting 'Thing'). With this change it passes.
  • cargo test -p rolldown --test integration: 2156 passed. 5 fail in my environment (test262_module_code, three cjs_module_lexer_compat fixtures, npm_packages/util_deprecate), and the same 5 fail on main, so they aren't related to this change. No existing snapshot changed.
  • cargo fmt --check, cargo clippy -p rolldown --all-targets -- -D warnings and the pre-commit vp check are clean.

AI disclosure: I used an AI coding assistant to investigate this and write the fix and the test. I reviewed the change and ran the tests locally.

…x as its exports

A module without module syntax is scanned as ExportsKind::None, so its
top-level `this` is mapped to `void 0`. When the link stage promotes it to
CommonJS because it is reached through require() (or a dynamic import with
code splitting off), switch that `this` to the module's exports object, as
Node does, and give the CJS closure its `this` binding.

Closes rolldown#11269
@hyfdev hyfdev self-assigned this Nov 6, 2026
@hyfdev
hyfdev marked this pull request as ready for review November 6, 2026 04:34
Copilot AI balanced review requested due to automatic review settings November 6, 2026 04:34
@netlify

netlify Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs canceled.

Name Link
🔨 Latest commit 8aaf5c7
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6aed5f747f7ff37c2c63613e

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.

🟡 Changes recommended

A dynamic-import-only .js target changes top-level this when code splitting is disabled; preserve the context replacements and add a regression confirming consistent behavior across splitting modes.

1 open issue
What changed in this PR

This PR addresses #11269 by updating Rolldown’s linker so syntax-free modules loaded through require() use their exports object for top-level this, fixing crashes in UMD-style dependencies.

Changes:

  • Adds a CommonJS promotion helper that updates top-level this bindings, used by require and no-splitting dynamic-import paths.
  • Adds regression fixtures for UMD-style initialization and direct this assignments.
  • Documents the linker’s new binding and symbol updates.
File Description
internal-docs/​linking/​determine-module-exports-kind/​implementation.md Documents promotion behavior and affected state.
crates/​rolldown/​tests/​rolldown/​issues/​11269/​main.js Asserts both required modules expose expected values.
crates/​rolldown/​tests/​rolldown/​issues/​11269/​lib/​thing.js Reproduces UMD-style top-level this usage.
crates/​rolldown/​tests/​rolldown/​issues/​11269/​lib/​index.js Loads syntax-free targets through require().
crates/​rolldown/​tests/​rolldown/​issues/​11269/​lib/​direct.js Covers direct assignment through top-level this.
crates/​rolldown/​tests/​rolldown/​issues/​11269/​artifacts.snap Records generated CommonJS wrappers and bindings.
crates/​rolldown/​tests/​rolldown/​issues/​11269/​_config.json Configures the regression fixture entry.
crates/​rolldown/​src/​stages/​link_stage/​determine_module_exports_kind.rs Adds and invokes the CommonJS promotion helper.

Review effort: Balanced

@codspeed

codspeed Bot commented Nov 6, 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 sarankumar1325:fix/cjs-this-required-js (8aaf5c7) with main (3132433)

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. ↩

…t code splitting

Also update the `cjs_this_ref` field doc and point `promote_to_commonjs` at the internal doc.

@hyfdev hyfdev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you!

@hyfdev
hyfdev merged commit 3ad9d79 into rolldown:main Nov 6, 2026
36 checks passed
This was referenced Nov 9, 2026
shulaoda added a commit that referenced this pull request Nov 9, 2026
## [1.3.1] - 2026-11-09

### 🚀 Features

- inline-common-chunks: inline chunks using `import.meta.ROLLDOWN_FILE_URL_*` (#11543) by @mattlewis92

### 🐛 Bug Fixes

- cli: apply --environment before loading the binding (#11553) by @Brooooooklyn
- rolldown_plugin_vite_resolve: escape module names in generated error stubs (#11584) by @sapphi-red
- add the code location to transform logs and errors at position 0 (#11568) by @chinmayajha
- match sticky regexes only at the start of the string (#11569) by @chinmayajha
- iife/umd: skip namespace markers when the entry has no exports (#11567) by @lazerg
- keep a declaration's name when it clashes with an external import (#11052) by @Nic-Polumeyv
- drop top-level statements made dead by imported constants before chunk linking (#11053) by @elliott-with-the-longest-name-on-github
- keep `this.resolve` custom options apart for overlapping calls (#11505) by @wan9chi
- transform: reuse TsconfigCache's answer when no tsconfig owns the file (#11265) by @sarankumar1325
- treat top-level `this` of a required module without module syntax as its exports (#11271) by @sarankumar1325
- keep side effects of a module whose exported constant is inlined (#11440) by @hyfdev
- leave same-chunk dynamic imports out of `dynamicImports` (#11156) by @kkkhs

### 🚜 Refactor

- prepend transferred imports as AST fragments (#11464) by @Dunqing

### 📚 Documentation

- show `vp` first in setup commands (#11503) by @IWANABETHATGUY

### ⚡ Performance

- incremental: reuse link-time facade symbols across rebuilds (#11542) by @mattlewis92
- incremental: share module sourcemap chains across cache clones (#11540) by @mattlewis92
- chunk_optimizer: answer runtime-merge reachability from one chunk-level graph (#11541) by @mattlewis92
- send only changed chunk properties back to Rust from output hooks (#11488) by @anonrig

### 🧪 Testing

- remove review fixtures committed by mistake in #11052 (#11574) by @hyfdev
- wasi: cover raw context destruction (#11561) by @Brooooooklyn

### ⚙️ Miscellaneous Tasks

- deps: update rust crates (#11573) by @renovate[bot]
- deps: update mimalloc-safe to 0.1.70 (#11589) by @shulaoda
- renovate: update GitHub Actions that are pinned to a commit (#11583) by @hyfdev
- skip Playwright browser downloads in Prepare Release (#11579) by @shulaoda
- pin the rolldown crates to exact versions of each other on release (#11577) by @shulaoda
- update `CodSpeedHQ/action` to v5.6.3 for Ubuntu 26.04 (#11575) by @hyfdev
- remove stale entries from `.typos.toml` (#11571) by @iiio2
- pick the Prepare Release target branch from the version (#11525) by @shulaoda
- run every OS on pushes to maintenance branches (#11520) by @shulaoda
- rebase maintenance Vite branches onto their Vite minor (#11515) by @shulaoda
- run CI on pushes to maintenance branches (#11516) by @shulaoda
- support patch releases from maintenance branches (#11393) by @shulaoda

### ❤️ New Contributors

* @chinmayajha made their first contribution in [#11568](#11568)
* @lazerg made their first contribution in [#11567](#11567)
* @elliott-with-the-longest-name-on-github made their first contribution in [#11053](#11053)
* @sarankumar1325 made their first contribution in [#11265](#11265)
* @anonrig made their first contribution in [#11488](#11488)
* @kkkhs made their first contribution in [#11156](#11156)

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.

Top-level this becomes undefined in a .js file that is loaded with require() but has no CommonJS markers of its own

3 participants