Skip to content

bundler: give a file that assigns require its own require variable - #46640

Closed
robobun wants to merge 5 commits into
mainfrom
robobun/aab4bbee/per-file-require-on-write
Closed

robobun wants to merge 5 commits into
mainfrom
robobun/aab4bbee/per-file-require-on-write

Conversation

@robobun

@robobun robobun commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • bun build of @node-rs/xxhash 1.7.6 exits 0. The bundle throws: Error: Failed to load native binding.
  • Its NAPI-RS loader runs require = createRequire(__filename). A bundle has one require (src/js_parser/visit/visit_expr.rs:319), so the copied .node file loads through the assigned one.

Fix

  • A file that assigns the free require declares var require2 = <the bundle's require> and uses it. Node gives each CommonJS module its own require. Calls that the bundler writes keep the bundle's require.
  • Exception: in cjs output the entry point is the output file. Its assignment still reaches every file (Node's single-executable idiom).
  • Verified: 76 new tests (test/bundler/bundler_cjs.test.ts, bundler_loader.test.ts, test/bake/dev/bundle.test.ts), 51 fail on main. Also bundler_edgecase, bundler_splitting, esbuild/default.
  • Self-reviewed: 38 concerns raised, 36 addressed. Rejected: a removable declaration (riskier), one binding with bundler: declare require inside a CommonJS wrapper whose body contains direct eval #35581 (for the second PR).

Background

  • The parser turns each free require into ERequireCallTarget. The printer spells it from Options.require_ref: __require in esm, require in cjs.
  • Considered: drop the assignment (the file's later calls ignore it). A require parameter on __commonJS (one of five file shapes).

Downsides

  • Behaviour change: in esm output, require = x in the entry point no longer reaches other files.
  • Cost: .text +7,504 B, one statement per assigning file (+22 to +75 B). Other files: +0 to +16 instructions per parse, +31 per print job, +6 per external require.
  • Still fails: browser and iife output. A literal require("./bundled") after the assignment loads the bundled file (lazy-cache, TypeError: Attempted to assign to readonly property. #11754).
Notes

Reproduction without native code

// node_modules/loader/index.js
const { createRequire } = require("node:module");
require = createRequire(__filename);
module.exports = "loader ok";
// node_modules/other/index.js
module.exports = () => require("ext");
// app.mjs
import loader from "loader";
import other from "other";
console.log(loader, "|", other());

Run bun build ./app.mjs --target=node --external ext --outdir=o. Copy the bundle and ext to a second folder. Move the source folder away. Run the bundle with Node.js.

cjs esm
main Error: Cannot find module 'ext' Error: Cannot find module 'ext'
this PR loader ok | ext of x/deploy loader ok | ext of x/deploy

@node-rs/xxhash 1.7.6, xxh32("made up", 7), node and bun targets, esm and cjs output: main fails in 4 of 4 cells (cause Cannot find module './xxhash.linux-x64-gnu-<hash>.node'). This PR prints 3318369215 in 4 of 4. esbuild 0.21.5 prints the same shared store as main (require = ... in cjs output, __require = ... in esm output).

The loader line comes from NAPI-RS (added 2024-10, removed 2025-10). Packages that were published in between carry it.

Output of the assigning file (node, esm)

// node_modules/loader/index.js
var require2 = __require;
var { createRequire } = require2("node:module");
require2 = createRequire(__filename);

Rules

  • Trigger: a store into the free require that can run, in any write form (=, ||=, ++, a destructuring target, for (require of ...)). The visit pass sets P::assigns_free_require at the place where the identifier becomes ERequireCallTarget. A store in dead code, in a with body, or one that a define replaced does not count.
  • Where: node and bun targets in esm and cjs output, and the dev server (Features::per_file_require). Not for a browser target: there require is a global that scripts share, and a browserify -r prelude assigns it for the other files. Not in iife output: the __require helper for node cannot load in a script (bundler: define __require in iife output #38077).
  • Entry point of a cjs bundle: it prints at the top level of the output file, so its require is the require that every file reads. The main script of a Node.js single executable application assigns it there (require = createRequire(__filename)), and main and esbuild 0.21.5 give that assignment to the whole bundle. generate_code_for_file_in_chunk_js drops the variable for chunk.is_entry_point_file(..). The same file keeps its variable where it is a dependency in a second output file.
  • First value: __require in esm output. typeof require === "undefined" ? undefined : require in cjs output, because cjs output can run where there is no require. hmr.require.bind(hmr) in the dev server.
  • Place: ahead of the imports of the file, and on the hoisted declaration of an __esm wrapper. In an import cycle another file can call a function of this file before its statements run.
  • Printer: Options.bundle_require_ref is what require_ref is for every other file. A lowered import or export * from, and import.meta.main, print it. In dev server output .resolve and .main keep the dev server form.
  • A require("literal") that the bundler resolved at build time does not go through the variable. NAPI-RS loaders need that. The lazy-cache idiom breaks on it.

Also fixed

  • --splitting: the store went to an imported __require and threw TypeError: Assignment to constant variable. (Attempted to assign to readonly property. in Bun).
  • --compile, --minify, Bun.build.
  • Dev server: hmr.require = x replaced the method that also loads the bundled requires of the same module, and stayed on the module across hot updates.

Left as on main

Measurements

Release builds. Tools: llvm-size, llvm-nm, gdb, perf_event instructions:u. valgrind, perf, strace and bloaty are not on the machine. The per-call counts are from the last commit. The other numbers are from the first commit against its base (5c6d4e2).

  • release binary .text: +7,424 B for the first commit (82,231,705 to 82,239,129, llvm-size -A). The later commits add 80 B of symbol size (llvm-nm -S: generate_code_for_file_in_chunk_js +112, to_ast +11 and -43). declare_own_require is 2,059 B in each of 2 monomorphs and #[cold].
  • visit pass: 4 lines changed under src/js_parser/visit (one branch on the require path). visit_expr_in_out +77 B in each of 2 monomorphs.
  • js_printer::Options 216 to 224 B. BundledAst +0 B (flag bit 3 of the existing u16). Ast +0 B. P +0 B. Expr unchanged at 16 B.
  • exact instructions for one call (gdb stepi, callees included, file module.exports = 1;, cjs output, 3 runs each):
    • _parse: 34,862 to 34,878 on main, 34,878 with this PR (+0 to +16).
    • print_code_for_file_in_chunk_js: 2,005 to 2,033 (+28).
    • generate_code_for_file_in_chunk_js, which calls it: +31. Its own instructions go from 402 to 405 for the entry point rule, with no cost per part.
    • print_require_or_import_expr for one external require("node:fs"): 510 to 516 (+6).
  • typescript.js bundle (no file assigns require): esm -565,649 of 1.0943e9 instructions, cjs -569,051 of 1.0921e9 (A/A floor 2,598 min, 284,464 median).
  • --no-bundle: 200,000 assignments -199,963 of 595.9M (floor 330). 10,000 requires -102 of 102.8M (floor 57).
  • printer: +5 instructions per printed external require over 500,000 printed (whole process), 0 per require with --no-bundle.
  • allocations (gdb counts on the 15 mimalloc entry points, whole bun build of one file): +0 for a file that does not assign require. +8 (esm) and +17 (cjs) for a file that does.
  • non-writer output: 229 of 229 corpus output files byte-identical (sha256sum, 252 builds: 12 entries, esm, cjs and iife, node, bun and browser, plain, --minify and --splitting). 0 existing bundler snapshots changed.
  • writer bundles: +1 statement per assigning file. esm +22 to +27 B, cjs +72 to +75 B, dev server +39 B. 0 stores into a shared require left in 15 of 15. __commonJS( and __toESM( counts unchanged.
  • life cycle of one module's require, 18 fields against Node.js: 16 of 18 equal (main 14 of 18). Still different: the typeof fold and the property write above.

Tests

  • test/bundler/bundler_cjs.test.ts: 69 new tests, 44 fail on main. The other 25 pin what must not change: the entry point of a cjs bundle, browser and iife output, import cycles, dead code, define, --banner, a with store, a direct eval, an unwrapped package. 20 todo rows record where a bundle still prints something else than its source.

  • The table requireAssignmentPrograms runs each program from source and from its bundle, with Bun and with Node.js, and compares the output.

  • test/bundler/bundler_loader.test.ts: 4 new tests with a copied .node file, 4 fail on main.

  • test/bake/dev/bundle.test.ts: 3 new tests (a server CommonJS file, a client module, a server ES module), 3 fail on main.

  • Other suites on the last commit: bundler_cjs2esm, bundler_edgecase, bundler_splitting, esbuild/default, esbuild/splitting. Four tests in them exceed a time limit in the debug build on the test machine and do not involve require: edgecase/DeepImportDiamondDAG (also on main's debug build), default/TopLevelAwaitForbiddenRequireSourceMapCLI, and two splitting/FoldingNeverMakesABundleWorse graphs that pass alone.

Self-review, not done

  • A declaration that tree shaking can remove. It needs the variable in the symbol uses of each part that reads require. The cost of the fixed statement is in the list above.
  • One binding for a file that has both a direct eval and an assignment. The PR that lands second passes the variable of bundler: declare require inside a CommonJS wrapper whose body contains direct eval #35581 as require_ref for that file in print_code_for_file_in_chunk_js.
  • A docs line for --banner, and an import record flag in place of was_unwrapped_require (it has no second reader).

Differences from the first design

  • The visit pass has one new branch. has_been_assigned_to of the require symbol is also set by a store in dead code, in a with body, and by one that a define replaced.
  • Browser and iife output are out. Both loaded on main and stopped loading with a per-file variable.
  • The entry point of a cjs bundle keeps the bundle's require. The first version gave it a variable too, which broke the single-executable idiom in a run with a require for built-in modules only.
  • The dev server variable starts as hmr.require.bind(hmr). hmr.importMeta.require throws ReferenceError: location is not defined on the server side.

Other open PRs at the same code

A bundle has one `require` for all of its files. An assignment to the
free `require` in one file changed it for every file, and for the calls
that the bundler writes itself: the load of a copied `.node` file, and
an `import` of an external package that the linker lowers to a call.

A file that assigns the free `require` now declares
`var require2 = <the bundle's require>` and reads and writes that
variable. The calls that the bundler writes keep the bundle's
`require`.

This applies to `--target=node` and `--target=bun` in esm and cjs
output, and to the dev server. Browser output and iife output do not
change.
@robobun

robobun commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:48 AM PT - Oct 24th, 2026

❌ @robobun, your commit 97a35ba has 2 failures in Build #131776 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 46640

That installs a local version of the PR into your bun-46640 executable, so you can run:

bun-46640 --bun

@robobun

robobun commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review.

How the bug was reproduced:

  • @node-rs/xxhash 1.7.6: bun build ./app.mjs --target=node --outdir=o, then node o/app.js. On main the bundle throws Error: Failed to load native binding in 4 of 4 cells (node and bun targets, esm and cjs output). With this PR it prints 3318369215 in 4 of 4.
  • The three-file case in the PR description shows the same without native code: main prints Error: Cannot find module 'ext', this PR prints loader ok | ext of x/deploy.
  • test/bundler/bundler_cjs.test.ts, test/bundler/bundler_loader.test.ts and test/bake/dev/bundle.test.ts: 51 of the 76 new tests fail on main. All pass with this PR.

CI on 97a35ba (build 131776): 179 of 181 jobs passed, and no bundler test failed. The two failed jobs do not touch this change:

  • test/js/first_party/ws/ws-proxy.test.ts on Windows x64. It also fails on main.
  • test/js/node/http/node-http-uaf.test.ts on macOS x64: should not crash on abort went over its 20 s limit.

Build 131625, on the commit before the last test-only commit, passed with 181 of 181 jobs.

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between bd0c395 and 97a35ba.

Files selected for processing: 1
  • test/bundler/bundler_cjs.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Walkthrough

The parser detects live assignments to free require and can create a per-file binding based on runtime features and output format. The bundler and printer preserve the distinction between that binding and the bundle-level reference. Tests cover assignment behavior across bundling scenarios.

Changes

Per-file require assignments

Layer / File(s) Summary
Assignment detection and per-file binding
src/ast/ast_result.rs, src/ast/nodes.rs, src/js_parser/*, src/bundler/ParseTask.rs
The parser tracks live assignments to free require. When enabled, it creates a per-file binding and records its ownership in the AST.
Bundler and printer reference selection
src/bundler/bundled_ast.rs, src/bundler/LinkerContext.rs, src/bundler/linker_context/generateCodeForFileInChunkJS.rs, src/js_printer/lib.rs
The bundler carries the ownership flag. Linker and printer code select the file-owned or bundle-level reference for generated calls and properties. Code generation also adjusts entry-point part processing and ESM wrapper hoisting.
Assignment behavior tests
test/bake/dev/bundle.test.ts, test/bundler/bundler_cjs.test.ts, test/bundler/bundler_loader.test.ts
Tests exercise assigned require behavior across targets, formats, loaders, generated calls, and dev-server updates.

Suggested reviewers: jarred-sumner

Priority: Normal

Merge Risk: Minimal · up to 97a35

No actionable merge-blocking risk is established by the reviewed changes.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly describes the main change: files that assign free require receive their own require variable.
Description check Passed The description is detailed and covers the problem, fix, scope, limitations, and verification results. It does not use the exact template headings, but it includes the required information, including …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and covers the problem, fix, scope, limitations, and verification results. It does not use the exact template headings, but it includes the required information, including extensive test evidence.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR

@claude claude Bot 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.

Beyond the inline findings, I also checked that the needs_wrapper_ref rewrite in src/js_parser/p.rs and the hoisting loop in src/bundler/linker_context/generateCodeForFileInChunkJS.rs stay complementary for non-own-require declarations (same predicate, negated), and that the generated require symbol goes through the linker's renamer so a user binding named require2 in the same file does not collide with it.

Extended reasoning...

The change adds a per-file require variable for files that assign the free require, touching the parser (new flag and part), the linker's hoisting condition, the printer's require spelling, and Ast/BundledAst flags, with no security-sensitive surface. Three inline findings were posted, including a behavior change for cjs entry files that rebind require, so a human look is already signaled; this note only records the two sibling-site checks that were ruled out.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread src/bundler/ParseTask.rs Resolved
Comment thread test/bundler/bundler_cjs.test.ts Resolved
Comment thread src/js_parser/p.rs Resolved
In cjs output the entry point is the output file itself. Its `require`
is the one that every file of the bundle reads, and the main script of
a Node.js single executable application assigns it there for the whole
bundle. The entry point of an output file now prints without its own
`require` variable. The same file keeps its variable where it is a
dependency in another output file.

Use `or_else` for the runtime `require` fallback (clippy `or_fun_call`).

Tests: remove the directories of the source and bundle comparison, and
keep the files that assign `require` off the entry point where the test
is about the variable.
Comment thread src/ast/ast_result.rs Resolved
Comment thread src/ast/nodes.rs Resolved
Comment thread src/bundler/LinkerContext.rs Resolved
Comment thread src/bundler/ParseTask.rs Resolved
Comment thread src/js_parser/p.rs Resolved
Comment thread src/js_parser/p.rs Resolved
Comment thread src/js_parser/p.rs Resolved
Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread src/js_parser/parser.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
@robobun

robobun commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

A note on the red robobun/evidence status for bd0c395. The change and the tests are as they were in a13ff62, and I found no defect in them.

That status comes from one release-build run of the three changed test files on a test machine. Three new tests went over the 5 second limit that itBundled sets for a release build outside CI:

  • bun/loader-napi-after-require-assignment-node-esm (5.0 s)
  • cjs/require_assignment_import_cycle_wrapper_esm_esm (5.0 s)
  • cjs/require_assignment_import_cycle_wrapper_esm_cjs (9.7 s)

The machine was slow during that run. DEV:bundle-4, a test that this PR does not touch, took 7.4 s in the same run and takes 0.7 s in other runs. The whole run took 68 s, against 33 to 37 s for the same command at other times.

The same three tests take 20 to 120 ms in every other run:

  • the debug (ASAN) run of the same check: all three pass with the change
  • CI on every platform (build 131546, and 179 of 181 jobs of build 131625 so far)
  • 5 more full release runs of the three test files on that machine, one of them directly after a rebuild of the release binary
  • 400 parallel runs of the two import cycle tests, and 1,500 builds and 1,500 runs of their fixture with the CLI

@claude claude Bot 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.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline finding, I checked the new commits against my earlier comments: the cjs entry-point case is now handled in generateCodeForFileInChunkJS.rs (the OWNS_REQUIRE_REF flag is cleared on the local BundledAst view that print_code_for_file_in_chunk_js reads, so the entry prints the ambient require and its own-require part is skipped), and the require_assignment test matrix now disposes its temp directories in afterAll. I also confirmed the AstFlags::OWNS_REQUIRE_REF bit round-trips in both BundledAst conversions and that js_printer::Options::default() initializes the new bundle_require_ref field.

Extended reasoning...

The change spans the parser (new assigns_free_require flag and declare_own_require part), the linker (entry-point special case, wrapper hoisting), and the printer (bundle_require_ref split), with a stated behavior change for esm output; it touches no security-sensitive surface. Two of three concerns from the prior review are addressed in the follow-up commits and the third was a deliberate design choice per the author; the one inline finding this run is a test-coverage nit. The size and the cross-crate semantics make this a change a human bundler owner should still read.

Comment thread test/bundler/bundler_cjs.test.ts Resolved
…pped without Node.js

The table left the Node.js cases out when the machine has no Node.js,
so a run passed with half of the table absent. They are now registered
and show as skipped.

@claude claude Bot 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.

I re-reviewed the latest push and found no new bugs; the points from my earlier passes (cjs entry point keeping the bundle's require, disposal of the matrix temp dirs, Node cases registered as skipped) are addressed in the code. Because this changes what require means inside bundled files across the parser, printer, and linker, a human maintainer should still weigh in on the design before merging.

What was reviewed:

  • declare_own_require initializers per output format and the unreachable! for IIFE — ParseTask.rs never turns per_file_require on for IIFE or browser targets, so it is not reachable from user input.
  • Part-index handling in generateCodeForFileInChunkJS.rs: the const assert pins OWN_REQUIRE_PART_INDEX == NAMESPACE_EXPORT_PART_INDEX + 1, and the index < first_other_part_index guard only skips the dropped part for the cjs entry-point case.
  • Printer split between require_ref and bundle_require_ref(): lowered import records and import.meta.main use the bundle's ref, require() calls use the file's own; require_ref_for_property falls back to the bundle ref only for dev-server output.
  • needs_wrapper_ref and the linker's hoist loop use the same can_be_moved() || own_require_ref predicate, so the two stay in sync.
Extended reasoning...

The change spans the JS parser (new assigns_free_require flag and declare_own_require synthetic part), the AST/BundledAst flags, the linker (per-file vs bundle require_ref, cjs entry-point exception, wrapper hoisting), the printer (new bundle_require_ref option and two helpers), and about 1,000 lines of new bundler, loader and dev-server tests. It touches no auth, crypto, or input-parsing surface; the reachable unreachable! was checked against the only setter of per_file_require. All three inline findings from prior runs are now addressed in code, and the most recent commit only touches test registration. Deferring rather than approving because the PR intentionally changes observable bundle semantics (a require assignment in one file no longer reaches other files in esm output) and introduces a format-dependent exception for cjs entry points, which is a design call for a bundler maintainer.

@robobun

robobun commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator Author

A note on the "Still fails" line: a literal require("./bundled") after the assignment (the lazy-cache idiom of clone-deep@0.2.4).

I built the opposite rule on top of this PR: a literal call after a store calls the stored function, as in Node.js. I do not propose it for merge. The branch is robobun/79555fee/lazy-cache-require-literal (c4d6ed0, +421 source lines).

What the branch does

  • The parser parses a file that stores a function into require a second time, with require as a variable of the file.
  • The variable starts as a function with a table: each specifier of the file loads its bundled module.
  • clone-deep@0.2.4, shallow-clone@0.1.2, merge-deep@3.0.3 and puppeteer-extra-plugin-stealth@2.11.2 then print the output of their sources. In place: 16 of 16 cells. From a folder with no node_modules: 16 of 16. As a --compile executable: 4 of 4. With this PR: 4, 0 and 0.
  • The todo row restored after a call with the literal of a bundled file passes there.

Why it is not a PR

  • It breaks bundles that work with this PR. Each build exits 0.
    • A real require that is stored in another form than require = f(__filename), f(module) or f(import.meta.url) loses its bundled literals. Example: const r = createRequire(__filename); require = r;. When the sources are gone, the bundle throws Cannot find module './dep.cjs'.
    • @sap/cds 10.2.1 throws RangeError: Maximum call stack size exceeded. Its lib/test/cds-test.js stores id => module.require(resolve(id, { paths })), and module.require prints as the variable of the file.
    • A literal that does not resolve in such a file is a throw at run time. With this PR it is a build error.
  • It reverses the rule that this PR states ("does not go through the variable"). esbuild 0.21.5 prints the same shape as main for the lazy-cache reproduction.
  • No open issue asks for it. TypeError: Attempted to assign to readonly property. #11754 and Attempting to compile puppeteer-extra-stealth-plugin fails (Attempted to assign to readonly property.) #13036 are closed. When the bundle of the TypeError: Attempted to assign to readonly property. #11754 program runs with no node_modules, it still stops later: puppeteer-extra loads each evasion with a computed require(name).

What works today, with no change in Bun

  • "overrides": { "clone-deep": "4.0.1" } in package.json. clone-deep 4 does not use lazy-cache. The Stealth() bundle then prints the output of its source from a folder with no node_modules, on main and with this PR.
  • --reject-unresolved. The build of clone-deep@0.2.4 fails with 3 errors at clone-deep/utils.js:11-13. It does not exit 0.

Question for a maintainer

After require = f in a CommonJS file, does a require("literal") that the bundler resolved call f (Node.js), or does it stay bundled (esbuild, this PR)? If the answer is "call f", the branch is a place to start, after repairs for the three cases above.

@robobun

robobun commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator Author

A note on the "Left as on main" line: with --target=browser --splitting, a store into an imported __require still throws.

The case

// a.js
import { publish, load } from "./writer.cjs";
publish(function (name) { return "published " + name; });
console.log("a:", load("x"));
// b.js
import { load } from "./reader.cjs";
console.log("b:", typeof load);
// writer.cjs
exports.publish = function (fn) { require = fn; };
exports.load = function (name) { return require(name); };
// reader.cjs
exports.load = function (name) { return require(name); };

bun build ./a.js ./b.js --target=browser --format=esm --splitting --outdir=out exits 0 on main (5e18294). node out/a.js then throws TypeError: Assignment to constant variable. (bun out/a.js: TypeError: Attempted to assign to readonly property.). The same build without --splitting prints a: published x. esbuild 0.25.1 prints the same store and throws the same error.

The page of a server build is the same case, with one entry point. Build a server that imports ./client.html with --target=bun --splitting, and let the script of the page run require = fn. The chunk of the page imports __require from the // @bun chunk and assigns it. A page file is a browser file, so by the target.is_server_side() rule in ParseTask.rs here it does not get the variable of this PR.

What I built

A fix on a branch. I do not propose it for merge: robobun/4f460940/require-store-across-chunks (01c68d8, +302 source lines in 15 files).

  • The parser marks the target of a store into require.
  • When the chunks are final, the linker finds the chunks that store and do not declare __require. The chunk that declares it then also exports var __requireStore = { get v() { return __require }, set v(value) { __require = value } }, and the store prints as __requireStore.v = fn.
  • I ran 21 forms of store on 3 targets, plain and minified. Each of the 126 split builds runs like the build without --splitting.
  • 0 of 264 output files differ from main across 58 builds that store nothing across a chunk (release builds of main and of the branch).

Why it is not a PR

  • It overlaps this PR. On node and bun it lets the split build share the stored require between files, as the build without --splitting does on main. This PR gives such a file its own require. Three tests of the branch pin the shared result for a bun target.
  • For the browser case alone it is large: a new ExprData variant, a flag on Part, and a statement that the linker adds to the runtime part after tree shaking.
  • A smaller shape exists: the same accessor as one statement of the runtime source, which the parser names for a store under --splitting. I did not build it. With it, every bundle parses one more runtime statement.
  • No issue reports the throw.

What works today, with no change in Bun

A module that every entry point imports, with export const store = { get v() { return require }, set v(value) { require = value } }, and store.v = fn in place of require = fn. I checked it on main for browser, node and bun targets. It needs an edit of the file that stores.

Question for a maintainer

For a browser target, does a store into require stay visible to the other files of the bundle, or does the file get its own require, as for node and bun? Main and the test cjs/require_assignment_browser_target_is_shared here keep it visible.

  • "Its own require": one arm of per_file_require in this PR then also covers --splitting for a browser.
  • "Visible to the others": the store needs the accessor. The branch has 10 browser tests for it.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-24.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants