Repository navigation
Conversation
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 7 minutes. View limit details
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. Comment |
|
Updated 9:11 AM PT - Oct 27th, 2026
✅ @robobun, your commit 111124029e214d9aaff07941eae573bc08d6d5ff passed in 🧪 To try this PR locally: bunx bun-pr 35665That installs a local version of the PR into your bun-35665 --bun |
|
Found 4 issues this PR may fix:
🤖 Generated with Claude Code |
|
Reproduced on main (8a0e49e), 1.4.1 and 1.4.3 with the default import form: // lib.cjs
exports.add = (a, b) => a + b;
exports.default = module.exports;
// app.mjs
import lib from "./lib.cjs";
console.log(lib.add(1, 2));bun build app.mjs --outfile o.js && bun o.js # ReferenceError: exports_lib is not defined1.4.0 and Node print 3. With The branch is rebased onto main (92e819d). PR: #35665 |
There was a problem hiding this comment.
I didn't find any bugs, but this touches the CJS→ESM unwrapping heuristic in the parser — a shared hot path whose record/ignore usage balance is subtle — so it's worth a human look.
What was reviewed:
- Traced the
record_usage(exports_ref)/ignore_usage(exports_ref)balance across themodule.exports→ESpecial::ModuleExportsrewrite and the consuming property-access arm; confirmed they cancel formodule.exports.fooand stay unbalanced when the value escapes. - Checked the deopt trigger at
parse_entry.rs:1499and that the extraexports_refuse is harmless whenunwrap_commonjs_to_esmis off (module_ref already forces CJS;commonjs_named_exportsstays empty). - Checked
is_control_flow_deadandcommonjs_named_exports_deoptimizedgating on both arms — no path records without the matching ignore being reachable except where deopt is already set.
Extended reasoning...
Overview
Two files changed. src/js_parser/fold.rs adds a record_usage(exports_ref) at the point where module.exports is rewritten to ESpecial::ModuleExports, and a balancing ignore_usage(exports_ref) in the ESpecial::ModuleExports target arm that fires when the value is immediately consumed by a static property access. When module.exports escapes as a value (function argument, computed index, stored), the unbalanced use makes uses_exports_ref true, which the existing check at parse_entry.rs:1499 uses to call deoptimize_commonjs_named_exports() and keep the module wrapped as CommonJS. Six new itBundled tests cover the rehackt/Object.assign pattern, generic escape, computed index, namespace import, and a negative regression check that plain module.exports.X = ... still converts.
Security risks
None. This is a bundler correctness change to symbol usage counting; no untrusted input parsing, auth, crypto, or filesystem behavior is touched.
Level of scrutiny
High. maybe_rewrite_property_access runs on every property access in every bundled file, and the CJS→ESM unwrapping decision affects tree-shaking and named-import resolution for any CommonJS module. The record/ignore pair lives in two different match arms with slightly different guards: the record is gated only on !commonjs_named_exports_deoptimized, while the ignore is additionally gated on should_unwrap_common_js_to_esm(). I traced why this asymmetry is safe (when unwrap is off, commonjs_named_exports is never populated so the parse_entry.rs:1499 deopt condition can't fire, and uses_module_ref is already true from the module identifier so exports_kind is unchanged), but a maintainer familiar with this code should confirm there's no other consumer of the exact exports_ref use count that this could perturb. The delete module.exports.foo path also records without ignoring (the delete-target early return precedes the new ignore_usage), but that path already calls deoptimize_common_js_named_exports() so the extra count is redundant, not wrong.
Other factors
The PR description states all 29 bundler_cjs2esm tests pass plus bundler_cjs, bundler_edgecase, bundler_npm, and the esbuild default/importstar/dce suites — that's the right coverage set for this change. The ModuleExportsPropertyReadStillConverts test with cjs2esm: true is a good regression guard against over-deoptimizing. The comments added are load-bearing (they explain the non-local record/ignore pairing). Given the blast radius of the shared code path and the subtlety of the balance, deferring for a human sanity check.
|
Of the four suggested, only #14939 is about this fault ( |
There was a problem hiding this comment.
I didn't find any bugs. The record/ignore balancing is sound and the test coverage is thorough, but this changes the CJS→ESM unwrapping heuristic in a way that affects how real npm packages get flattened, so it's worth a maintainer sanity-check.
What was reviewed:
- Traced the deopt path: unbalanced
record_usage(exports_ref)→uses_exports_ref→deoptimize_commonjs_named_exports()at parse_entry.rs:1499 →is_deoptimized_commonjs()→ExportsKind::Cjs. - Confirmed
ESpecial::ModuleExportsis only produced at fold.rs:349, so every instance reaching the balancing arm has a matchingrecord_usage. - Checked the
should_unwrap_common_js_to_esm() == falseimbalance is benign (module_ref stays used, so the module was already CJS); same for theis_delete_targetearly-return beforeignore_usage. - Both sides are consistently gated on
!is_control_flow_dead/!is_revisit_for_substitution.
Extended reasoning...
Overview
Two files touched: a 6-line change in src/js_parser/fold.rs (maybe_rewrite_property_access) and 7 new itBundled cases in test/bundler/bundler_cjs2esm.test.ts. The Rust change adds record_usage(exports_ref) where module.exports is rewritten to ESpecial::ModuleExports, and a balancing ignore_usage(exports_ref) where that special is immediately consumed by a static property access. When module.exports escapes as a value (Object.assign target, computed index, function argument), the use stays unbalanced, uses_exports_ref flips true, and the existing deopt at parse_entry.rs:1499 keeps the module wrapped as CommonJS instead of synthesizing an incomplete ESM export set.
Security risks
None. This is a build-time bundler heuristic; no untrusted input parsing, no auth/crypto/permissions surface.
Level of scrutiny
Medium-high. The diff is tiny, but the CJS→ESM unwrapping heuristic is load-bearing for how thousands of npm packages get flattened in --target=bun and --compile. The correctness of the fix depends on a cross-call invariant (record in the inner module.exports visit, ignore in the outer .foo visit) holding under all the surrounding gates. I verified the invariant against the current gates: both sides are guarded by !is_control_flow_dead / !is_revisit_for_substitution (via record_usage/ignore_usage themselves), and the record side is additionally inside !commonjs_named_exports_deoptimized which the ignore side matches. The one asymmetry — record fires regardless of should_unwrap_common_js_to_esm() but ignore requires it — is benign because module_ref is never ignored on this path, so uses_module_ref was already forcing CJS in that configuration. The is_delete_target early-return before ignore_usage also leaves an unbalanced use, but that path calls deoptimize_common_js_named_exports() anyway.
Other factors
Test coverage is strong: named import, namespace import, the exact rehackt shape with the dead if (0) hint, computed index, arbitrary function escape, the wasm-bindgen shape from #14939, plus ModuleExportsPropertyReadStillConverts as a regression guard that pure module.exports.X = Y modules still flatten (cjs2esm: true asserts no __commonJS wrapper). The author reports the full bundler_cjs2esm suite plus bundler_edgecase, bundler_npm, and the esbuild suites are clean. Deferring because a maintainer should confirm they're comfortable with the balancing approach vs. e.g. threading an explicit "escaped" flag, and because changes to this heuristic have historically had long tails in the npm ecosystem.
2fae94a to
b5d5e2c
Compare
|
Rebased onto main at 3ff3579 and re-verified: the real |
There was a problem hiding this comment.
I didn't find any bugs. The record/ignore balance is sound and the regression guard (ModuleExportsPropertyReadStillConverts) confirms straightforward module.exports.X still unwraps. That said, this adjusts the CJS→ESM unwrapping heuristic in the parser — a subtle area where the failure mode is silent bundle-size regression for packages that were previously flattened — so it's worth a maintainer look.
What was reviewed:
- Verified
record_usage/ignore_usageare symmetric (both gated on!is_control_flow_dead && !is_revisit_for_substitution) and that the unbalanced use hits the existing deopt atparse_entry.rs:1441. - Checked the
should_unwrap_common_js_to_esm()gate asymmetry between the record site and the ignore site — it's correct: when unwrapping is off,ESpecial::ModuleExportsstays in the output and prints asexports_ref, so the recorded use is accurate. - Confirmed both
maybe_rewrite_property_accesscallers (EDot and EIndex-with-string-key invisit_expr.rs) reach the balancing arm; onlyoptional_chainskips it, which safely deopts.
Extended reasoning...
Overview
The PR changes 4 lines of logic in src/js_parser/fold.rs::maybe_rewrite_property_access and adds 7 itBundled cases to test/bundler/bundler_cjs2esm.test.ts. The fix records a use of exports_ref when module.exports is rewritten to ESpecial::ModuleExports, and balances it with ignore_usage when that node is immediately consumed as the target of a property access. Net effect: a bare/escaping module.exports value leaves an unbalanced use, making uses_exports_ref true and triggering the pre-existing deopt in parse_entry.rs so the module stays wrapped as CommonJS instead of being flattened with an incomplete static export set.
Security risks
None. This is compile-time bundler heuristics with no untrusted-input parsing, no allocation sizing, and no runtime code.
Level of scrutiny
High. The CJS→ESM unwrapper decides whether npm packages get flattened for tree-shaking. The change is small and the direction of failure is safe (over-deopt → wrap, which is always semantically correct), but the record/ignore pairing depends on the exact visit order and gate conditions matching between two separate match arms. I traced the callers in visit_expr.rs — both the EDot path (line 1423) and the EIndex-with-string-literal path (line 1037) route through maybe_rewrite_property_access and reach the balancing ESpecial::ModuleExports arm. The optional_chain.is_none() guard on both callers means module.exports?.foo would leave an unbalanced use and deopt, which is a harmless (and vanishingly rare) over-conservatism. The is_delete_target early-return in the ModuleExports arm skips the ignore_usage, but that path already calls deoptimize_common_js_named_exports() so the extra use is moot.
I also checked the gate asymmetry: record_usage is not gated on should_unwrap_common_js_to_esm() while ignore_usage is. This is correct — when the option is off, the ESpecial::ModuleExports node is not rewritten to a CommonJSExportIdentifier and prints as exports_ref, so the recorded use accurately reflects the output. And with the option off, commonjs_named_exports stays empty so the parse_entry.rs:1441 deopt condition (count() > 0) can't fire spuriously.
Other factors
Test coverage is thorough: five deopt shapes (Object.assign, dead-hint rehackt pattern, namespace import, function-arg escape, computed index, wasm-bindgen store-before-assign) plus one regression guard proving the simple property-access case still converts with cjs2esm: true. The author reports bundler_cjs, bundler_edgecase, bundler_npm, and the esbuild suites show no new failures, and verified against the real @apollo/client+rehackt and @swc/wasm-typescript reproductions. I'm deferring rather than approving because this is a heuristic change in core bundler logic where the interesting risk — a common npm shape that was previously unwrapped now getting wrapped — wouldn't show up as a test failure, only as a bundle-size regression, and a maintainer who owns this code is better placed to judge that.
|
Verified this also covers the entry-file form of the bug (no importer at all), in addition to the side-effect import form: // lib.cjs, built as the entry: bun build --target=browser lib.cjs
module.exports.answer = 42;
console.log(typeof module.exports); // 1.4.3 bundle: "undefined"
console.log(Object.keys(module.exports).join()); // 1.4.3 bundle: ReferenceError: exports_lib is not definedWith the two |
|
I ran the used-import forms of this bug on main ( Library shapes (
Import forms:
The counts are per mode, and they are the same for Silent form // lib.cjs
exports.a = 1;
exports.b = 2;
exports.out = Object.keys(module.exports);
// app.mjs
import lib from "./lib.cjs";
console.log(JSON.stringify(lib.out ?? lib.add(1, 2)));
Emitted code, shape 1 with // main
var $add = (a, b) => a + b;
var $default = exports_lib; // never declared
console.log($add(1, 2));
// main + this PR
var require_lib = __commonJS(function(exports, module) {
exports.add = (a, b) => a + b;
exports.default = exports;
});
var import_lib = __toESM(require_lib(), 1);
console.log(import_lib.add(1, 2));What still lifts with this PR: a file that only writes For the rebase
|
…orts` value behind `bun build` with ESM output lifts a CommonJS file that has `exports.x = ...` lines into ES module exports. It did that even when the file also used `module.exports` as a value (`exports.default = module.exports`, `Object.assign(module.exports, ...)`, `Object.keys(module.exports)`). The value then printed as `exports_<file>`, a name that nothing declares, or as a stand-in object that has every key before the first statement runs. The parser makes one ESpecial::ModuleExports node for each `module.exports` and counts it (module_exports_rewrite_count, #41262). The lift consumes a node when a property access turns it into `$name`. Count those too (module_exports_lifted_count). When the parser made more nodes than the lift consumed, and a statement that is not removed still uses `module`, the file keeps its `__commonJS` wrapper. It then has one real exports object. A node that the --minify-syntax substitution revisit consumes is not counted, because the revisit does not record the use of `$name`. Fixes #12518
module.exports value behind
b5d5e2c to
9ac77ed
Compare
There was a problem hiding this comment.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟡
src/js_parser/parse/parse_entry.rs— Bundles of a CommonJS file that also contains a top-levelawaitand touchesmodule.exportsas a value now fail to load with a SyntaxError, where the base produced a bundle that ran when the value branch was cold. The force_esm break at src/js_parser/parse/parse_entry.rs:1591-1597 fires only when every export is a bare read, so a file withexports.a = 1,if (cond) globalThis.lib = module.exportsandawait xfalls through to the new arm at parse_entry.rs:1610 and keeps a wrapper;awaitinside the__commonJSfunction is a SyntaxError. Fix: never wrap a file that has top_level_await_keyword or esm_export_keyword set; route those through the force_esm path, or report a build error that names the file, instead of printing an unparseable bundle.Why this was flagged
Trigger: a
.jsfile withexports.a = 1; if (typeof window !== "undefined") window.lib = module.exports; await Promise.resolve();bundled to ESM for a server target. has_es_module_syntax is set by the top-level await, but needs_decl_count is 0 becauseexports.ais assigned, so parse_entry.rs:1594 does not take the force_esm break. parse_entry.rs:1604 does not fire (use 1, rewrite 1). parse_entry.rs:1610 fires (rewrite 1 > lifted 0, use 1) and calls deoptimize_commonjs_named_exports at parse_entry.rs:1616, so parse_entry.rs:1917 sets ExportsKind::Cjs before the top_level_await_keyword check at parse_entry.rs:1919. The linker then wraps the body in a non-async__commonJSclosure and theawaitis a syntax error at load; the base lifted the file and the undeclaredexports_libreference threw only if the cold branch ran. Population: bundle authors with mixed files that Bun's runtime accepts; the build still exits 0, so the failure surfaces at deploy. Remedy: exclude files with a top-level await or ES export keyword from the new arm and emit a diagnostic.Verification: Trigger: a bundled-to-ESM file with lifted
exports.a = 1, a livemodule.exportsvalue use and a top-levelawait. The new arm at src/js_parser/parse/parse_entry.rs:1610-1616 fires and the deopt check at 1917-1920 wins over the TLA check, so the file getsWrapKind::Cjsandawaitlands inside a sync function: SyntaxError at load. On base exports_kind is Esm via 1919 and the bundle runs whenever the value branch is cold. -
🟡
src/js_parser/p.rs— Users who build with tree shaking off, or a file with a top-levelusing, get a CommonJS wrapper and lose static named exports for files whose onlymodule.exportsvalue use the parser already removed. With one part (src/js_parser/parse/parse_entry.rs:1108) the dead-part rollback at src/js_parser/p.rs:5552 never runs, somodulekeeps the use from a removed(function(){ return module.exports })while the counters at src/js_parser/fold.rs:444 and fold.rs:734 are never rolled back; parse_entry.rs:1610 then wraps. Fix: roll back module_exports_rewrite_count and module_exports_lifted_count together with the use counts of a removed statement, in both the per-statement and single-part paths, so the verdict reflects only live statements.Why this was flagged
Trigger:
exports.y = 1; (function unused() { return module.exports; });bundled with tree shaking disabled or with a top-levelusingin the file, which puts every statement in one part (src/js_parser/parse/parse_entry.rs:1108-1110). The visit removes the unused function expression, but src/js_parser/p.rs:5503-5562 only clears use counts when the whole part is empty, somodulekeeps use 1. src/js_parser/fold.rs:444 counted 1 rewrite, fold.rs:734 counted 0 lifts. parse_entry.rs:1610 sees 1 > 0 && 1 > 0 and wraps. On the base the same file is lifted (first arm: 1 > 1 is false), and ModuleExportsValueOnlyInRemovedStatementStillConverts pins the lift only for the default tree-shaking configuration. Consequence: the entry-point form printsexport default require_x();only andexport *from an ESM wrapper exposes no names, so named imports of the bundle fail at load, plus +1.3 KB per file. Population: Bun.build callers with treeShaking disabled and every file with a top-levelusing. Remedy: decrement both counters when a statement that produced them is removed.Verification: nit — triggered when the whole file is one part (src/js_parser/parse/parse_entry.rs:1108-1110) and a side-effect-free top-level expression statement contains
module.exportsas a bare value. The rollback runs only whenpart_stmtsis empty (src/js_parser/p.rs:5552), somodulestays at use 1. On the base commit the same file is lifted.
|
On the two optional findings: Top-level Single part with tree shaking off, or with a top-level |
…y-syntax `import alias from "./alias.cjs"; alias.get()` binds the lifted `get`, as a named import does. With --minify-syntax, a file that reaches its exports through `const m = module` or `const m = module.exports` printed `$a is not defined` for that form since 1.4.1. The named import form was the only one in the test.
Fixes #12518
Related to #14939
Problem
bun buildlifts a CommonJS file to ES exports (no__commonJSwrapper), even one that usesmodule.exportsas a value. That bundle throwsReferenceError: exports_lib is not definedor reads wrong data, and the build exits 0.src/js_parser/parse/parse_entry.rs:1600) did not test for amodule.exportsvalue.Fix
module.exportsnodes that the lift turns into$name(module_exports_lifted_count). bundler: keep the CommonJS wrapper when a file uses module beyond module.exports #41262 counts the nodes made.moduleused in a live statement: the file keeps its wrapper, as Node and esbuild do.test/bundler/bundler_cjs2esm.test.ts(25 of 139 fail on main), 640 of 640 matrix cells equal Node (main 352), 30 bundler suites.Background
exports.foo = xprints asvar $foo = x.exports_refuse count (misses a value that--minify-syntaxinlines), a linker re-wrap (the parser still publishes the wrong lift).Downsides
export * fromsuch a file in an ESM entry exports no names, like every wrapped CommonJS file (Bun.build commonjs named exports conversion to ESM is broken #12463).import { y }fails at link andns.yisundefined.using(--target=node,browser) its exports readundefineduntil js_parser: split a lifted CommonJS export into a declaration and a store when lowering top-levelusing#45562 lands. Parse cost: +3 instructions per liftedmodule.exports.x.Notes
Repro (the default import form, a regression in 1.4.1)
bun build app.mjs --outfile o.js && bun o.jsprints 3 on 1.4.0 and with this PR. On 1.4.1, 1.4.3 and main it throwsReferenceError: exports_lib is not defined. The silent form isexports.a = 1; exports.b = 2; exports.out = Object.keys(module.exports);. Node prints["a","b"]. main prints["a","b","out"], because the stand-in object gets every key before the first statement runs.The older forms never worked: a named import,
import *, a side-effect import and the file as the entry point (#12518, #14939). On main the realrehackt@0.1.0file overreactthrowsTypeError: undefined is not a function.How the verdict works
maybe_rewrite_property_access(src/js_parser/fold.rs) turns eachmodule.exportsinto oneESpecial::ModuleExportsnode and adds 1 tomodule_exports_rewrite_count. When a property access follows (module.exports.foo), the same function turns the node into$foo. That is the only consumer. It now adds 1 tomodule_exports_lifted_count.Parser::_parseruns once per file, after the visit. The new arm keeps the wrapper whenmodule_exports_rewrite_count > module_exports_lifted_countand the use count ofmoduleis not 0.modulecovers that case: if no statement that stays usesmodule, then nomodule.exportsnode stays, and the file is lifted as on main. A file that keeps its wrapper through this arm always has a use ofmodule, so the wrapper bindsexportsandmodule.--minify-syntaxvisits an expression again after it inlines a single-useconst. That revisit records no symbol uses, so a node that it turns into$nameis not counted:const m = module.exports; return m.a + 1keeps the wrapper with and without the flag.--format=cjs,--format=iifeand the runtime transpiler do not lift, and their output does not change.Merge order
src/js_parser/p.rs(the field next tomodule_exports_rewrite_count, which js_parser: roll back a removed statement's tracked uses along with its use counts #45345 replaces withmodule_exports_rewrites: AccountedUses), and the new arm reads that counter. The PR that lands second takes these edits: the lifted count becomesmodule_exports_lifted: AccountedUses, the consumer calls.note(p.part_generation)under the revisit test,revert_dead_partreverts it next tomodule_exports_rewrites, and the arm compares the two totals. If js_parser: roll back a removed statement's tracked uses along with its use counts #45345 lands first, I rebase this PR in that way./alias.cjsincjs2esm/RemovedModuleExportsReadKeepsWrapper_{cli,api}and/aliased.cjsincjs2esm/VarWithTheNameOfModuleOrExportsKeepsWrapper. Wrapped is the intended verdict for both: on main,import { get }from/alias.cjswith--minify-syntaxthrows$a is not defined, and so does a default import that only callsalias.get()(right on 1.4.0, a regression in 1.4.1). Both rows move to thecjs2esm.unhandledlist in the PR that lands second.cjs2esm/ModuleExportsValueBesideRemovedStatementfails if a merge leaves the new arm dead.using#45562 removes limit 3 below. Measured on a release build of this PR with js_parser: split a lifted CommonJS export into a declaration and a store when lowering top-levelusing#45562 merged: theusingcase prints1 a 2for--target=node,browserandbun, as Node does. The Rust hunks do not overlap.exportsin a CommonJS wrapper that prints lifted exports #46565 and bundler: take one copy per key for a top-level destructuring of a module namespace #46163 have no overlap in the Rust files. They add tests at the end of the same test file.Known limits, with the owner of each
export default require_x();only. Behindexport * fromin an ESM entry it gives no names:import { y }from the bundle fails at link, andns.yisundefinedat exit 0. This is true for every wrapped CommonJS file on main (Bun.build commonjs named exports conversion to ESM is broken #12463):exports.add = ...; exports.keys = Object.keys(exports).join();behindexport *fails in the same way on main, and Node exportsadd. esbuild 0.21.5 and 0.28.2 print the sameexport defaultfor 9 of 9 package files. This PR moves the files that usemodule.exportsas a value into that group. On main they are lifted, soexport *over them works: 24 of 24 cells (12 library shapes, a named import and a namespace read) go from right to wrong.export { add } fromworks. Effect on bun build generates undefined variable when bundling @swc/wasm-typescript #14939: the undeclaredexports_wasmis gone and the file loads, but the reporter'simport { transform }from the bundle of the CommonJS entry fails withdoes not provide an export named 'transform'. A default import of the bundle works, and so does an ESM entry withexport { transform } from "@swc/wasm-typescript".exportor a top-levelawaitnext to a livemodule.exportsvalue now gets the wrapper. The ES export then readsundefined(2 1becomesundefined 1), and the top-levelawaitis aSyntaxErrorat load. main does the same today for the bareexportsspelling of the same files. Node cannot load these files at all. Owner: js_parser: make the ESM/CJS classification and the module/exports bindings agree #40840, js_parser: do not bind module or exports in a file whose module type is ESM #46037.usingin a file that now keeps its wrapper, for--target=nodeand--target=browser:ReferenceError: exports_lib is not definedbecomesundefinedexports at exit 0.--target=bunis right. The lowering ofusingdoes this to every wrapped file on main. Owner: js_parser: split a lifted CommonJS export into a declaration and a store when lowering top-levelusing#45562. With js_parser: split a lifted CommonJS export into a declaration and a store when lowering top-levelusing#45562 merged on this PR, the case prints1 a 2for all three targets.require()(for examplerequire("scheduler")inreact-dom) of a package that now keeps its wrapper gets a__toESMcopy: the object has adefaultkey and is not identical tomodule.exports. Every wrapped package on that list has this on main. Owner: bundler: skip __toESM for an unwrapped require() of a package that keeps its CommonJS wrapper #46215.var exports = module.exports) keeps the wrapper. The output is right. The bundle grows by 1370 to 1381 B, and such a file as the entry exportsdefaultonly. None of the 340 package files of the census below has this shape. A removed statement that holds the value next to a livemodule.exports.xkeeps the wrapper too, until js_parser: roll back a removed statement's tracked uses along with its use counts #45345 rolls both counters back.force_esmbreak, is not touched:module.exports["§"] = () => {}; export const b = 1;still prints an undeclaredexports_b. Owner: js_parser: make the ESM/CJS classification and the module/exports bindings agree #40840, js_parser: do not bind module or exports in a file whose module type is ESM #46037.module.exportsstill prints as the wrapper'sexportsparameter after code replacesmodule.exportsthrough an alias ofmodule. Same output on main. This is follow-up work.--minify, a file that the linker of main already put back into a wrapper gets other minified names, at the same size (39 of 48 matrix cells).exportsas a value on main. Measured: 300 files with 20 exported functions and one export that returnsmodule.exports, and an app that imports one function from each. main 30,803 B (18,112 B with--minify), this PR 484,543 B (301,979 B). Withexportsin place ofmodule.exportsin the same files, main and this PR both print 482,444 B. On main the small output is right only while nothing calls the export that returnsmodule.exports.Can
export *keep the names that the file assigns statically?Yes, for the static names, but it needs linker work that is not in this PR.
commonjs_named_exportsfor a file that it leaves wrapped, and that map reaches the linker. For a file that this PR wraps, every name in it has a top-level assignment.export *over every CommonJS file (ExportStarContext::add_exports). Each name would have to become a property read off the wrapper's result.export *of a wrapped lifted CommonJS file at bundle time #46936 (open) builds that read for a file that the parser lifted and the linker wrapped. It printsvar export_foo = ns.foo; export { export_foo as foo }. It does not cover a file that the parser keeps wrapped, for two reasons.record_exportleavesnamed_exportsempty for such a file, and bundler: resolveexport *of a wrapped lifted CommonJS file at bundle time #46936 readsnamed_exports. And bundler: resolveexport *of a wrapped lifted CommonJS file at bundle time #46936 treats the list as complete and drops the run-time__reExport, but a file that usesmodule.exportsas a value can add names at run time (Object.assign(module.exports, require("react"))), so the run-time path has to stay for reads inside the bundle.export *of a wrapped lifted CommonJS file at bundle time #46936 plus a flag that marks these files as static. The barrel declaresvar lib = __toESM(require_lib(), 1);and exports no name. So the extension needs the names fromcommonjs_named_exportsand a mode that keeps the run-time fallback. That is work on top of bundler: resolveexport *of a wrapped lifted CommonJS file at bundle time #46936.Measurements (release builds of main 8a0e49e and of this diff on it, Linux x64, Node v26.3.0 as the yardstick)
require(),import(), side-effect,export *, entry,import()with--splitting) x 4 configs (--target=node,bun,browser,node --minify). 640 of 640 cells equal Node. main: 352 (276ReferenceError, 8 silent, 4 failed builds). All 160 control cells print the same as on main, and their bundles are byte-identical. No cell of this matrix is right on main and wrong here. Itsexport *form is a barrel inside the bundle. An ES entry withexport *is limit 1: 24 of 24 cells go from right to wrong.module.exportsas a value: 9 change, all from an undeclaredexports_<file>to a wrapper (ansi-escapes 4.3.2, vite 6.2.3index.cjs, mysql2 3.7.0lib/packets/index.js, @npmcli/fs 3.1.1lib/cp/errors.js, @swc/wasm and @swc/wasm-typescript 1.16.20wasm.js, @prisma/prisma-schema-wasm 5.22.0, rehackt 0.1.0index.jsandrsc.js). On main 9 of 9 throw at load. Here 9 of 9 load. Otheresmoresm --minifyoutputs changed: 0.iifeandcjsoutputs changed: 0.export defaultonly. @swc/wasm-typescript behindexport *: 64 names to 0.module(exports.get = function () { const m = module; return m.exports.a + 1; }), 3 import forms x 4 flag sets (none,--minify-syntax,--minify,--production): 6 of 12 bundles differ from the unbundled program on main (ReferenceError: $a is not defined), 0 of 12 here. 1.4.0: 4 of 12. 1.4.1: 6 of 12.cmp).export *inside a bundle +359 to +425 B (36 of 42 cells), a default import read by property +894 B (3 of 9 cells), the shapes of limit 5 +1370 to +1381 B (11 of 39 probed rows). All of them equal Node. No wrapper is printed without anexportsparameter.module.exports.xstatement +3, anexports.xstatement +1, a plaina.b.c;+0,--format=iife+0.Parser::_parse: +15 for a file with 12 liftedexports.x, +42 with 12 liftedmodule.exports.x, +0 for a plain file in a bundle and underbun run.size_of P4080 to 4080 bytes (theu32takes the tail padding). Release.text+0 B, file size ofbun+0 B.maybe_rewrite_property_access-5 B,Parser::_parse+8 B and +5 B,P::init-7 B (nm -S). 8 of 140,561 sized symbols differ.Tests
bun bd test test/bundler/bundler_cjs2esm.test.ts: 139 pass. On a release build of main: 114 pass, 25 fail.export *), eight parent expressions (typeof,in,?., spread,module["exports"], a computed key, a nested function with a localexports, destructuring), the entry point, a side-effect import,import()with--splitting, a React-familyrequire(), a TypeScript file withimport type, a deadexports = {}, a removed statement next to a live value,--minify-syntaxaliases (const m = moduleandconst m = module.exports, through a named import and through a default import that only callsget()),--target=bun,Bun.buildwithminifyIdentifiers, andrehackt@0.1.0/index.jsas it is over a lifted and over a wrappedreact.module.exports, a read in dead code, a read in a statement that the parser removes.cjs2esm/DeleteFoldedModuleExportsRefpinned the undeclared name and said the bundle cannot run. It now runs.bundler_cjs,bundler_edgecase,bundler_minify,bundler_splitting,bundler_barrel,bundler_npm,bundler_regressions,bundler_browser,bundler_bun,bundler_jsx,bundler_string,bundler_loader,bundler_plugin,bundler_drop,bundler_naming,bundler_comments,bundler_feature_flag,bundler_defer,esbuild/default,esbuild/importstar,esbuild/importstar_ts,esbuild/dce,esbuild/extra,esbuild/packagejson,esbuild/ts,esbuild/tsconfig,esbuild/splitting,esbuild/loader,transpiler/preserve-use-strict-cjs,transpiler/function-tostring-require. The one failure,default/TopLevelAwaitForbiddenRequireSourceMapCLI, is a 5 s timeout that the debug build of main has too.Self-review
module(no wrapper for a value that only a removed statement holds, and no count ofexportsuses), one-line comments, two tests with the realrehacktfile overreact.Related to #14939in place of a closing keyword, the merge order, and the limits with their owners.exportsof limit 7, and a check in theitBundledharness for a generated name that nothing declares.import os from "node:os"; globalThis.hasFoo = !!exports.foo;, which prints an undeclaredexports_lib. Node throwsReferenceError: exports is not defined in ES module scopefor the same file.History
The first version of this PR (July) recorded a use of
exports_refat the rewrite and took it back at the property access. It had the same outcome for the first visit. It missed themodule.exportsthat the--minify-syntaxrevisit makes or takes (const m = module.exports; return m.a + 1printed$a is not defined), and it changed the shared use count for output formats that never lift. Its seven tests are kept.[review] gate passed · iteration 2 · 2 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 2
evidence per changed file