Repository navigation
Conversation
A CSS file's source index carries both its stylesheet and the lazy-export
JS stub that JS importers see. When the stub is require()d (or import()ed
without splitting) it is CommonJS-wrapped and generate_code_for_lazy_export
turns its lazy-export part into `module.exports = <class map>`, but the
tree-shaking pass returned from the CSS branch before walking the file's
parts, so that part was never live and the wrapper was printed with an
empty body: require("./x.module.css") returned {}.
mark_file_live_step now falls through to the normal parts walk for a
CommonJS-wrapped CSS file. mark_file_reachable_for_code_splitting follows
the dependencies of a CSS file's live parts, so the runtime that defines
__commonJS (or __export, for a namespace import) lands in the chunk that
prints the stub, without putting it into chunks that merely link a
stylesheet. Wrapping a file no longer propagates through a CSS file's own
import records (@import, url(), composes), which only produced empty
init_* closures for the referenced files.
|
Updated 5:05 AM PT - Aug 14th, 2026
❌ @robobun, your commit c482c44 has some failures in 🧪 To try this PR locally: bunx bun-pr 38307That installs a local version of the PR into your bun-38307 --bun |
|
Status: fix pushed, CI nearly through (177 of 179 Buildkite jobs passed, none failed, at the time of writing); the automated reviews raised nothing to change. The overlap with #38286 is described in the PR body and in a note on that PR; merge order between the two is the one thing that needs a human call. Reproduced with the released 1.4.0: |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughChangesThe bundler now traverses live CSS dependencies during code splitting and preserves CommonJS CSS wrappers during tree shaking. Dependency wrapping excludes stylesheet imports from JavaScript wrapper propagation. CSS module tests cover these behaviors. CSS CommonJS bundling
Suggested reviewers: Merge Risk: ⚪ Minimal · up to This change restores CSS module exports for CommonJS-style loading and removes inert asset initialization; the supplied regression coverage and clean checks leave no actionable merge-blocking risk at the current head. 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. The three linker changes (tree-shaking fall-through for CJS-wrapped CSS, live-parts-only reachability for CSS stubs, and skipping wrap propagation into a stylesheet's import records) are each well-argued and pinned by tests, but they touch core bundler tree-shaking / code-splitting control flow and overlap with #38286 on the same lines, so a human look is worthwhile.
What was reviewed:
mark_file_reachable_for_code_splitting: verifiedparts_liveis populated (tree shaking runs first, line 907 before line 939) and the outer&mut parts_livereborrow is consumed byTreeShakeCtxbefore this reads it viaself.mark_file_live_step: theWrapKind::Cjsgate falls through to the normal parts walk; the HTML branch below it doesn't fire for CSS, andinternal_bake_devnever setsCjson CSS so it's unaffected as claimed.DependencyWrapper::wrap: the CSS-file guard sits afterdid_wrap_dependencies/wrapare set, so the CSS stub itself is still wrapped — only the descent into@import/url()/composesrecords is skipped.
Extended reasoning...
Overview
Three targeted changes in the bundler linker to make require('./x.module.css') (and import() without splitting) emit a working CommonJS wrapper:
src/bundler/LinkerContext.rs:mark_file_live_step— a CSS file withWrapKind::Cjsfalls through to the normal parts walk after following its stylesheet import records, so themodule.exports = {...}lazy-export part becomes live.mark_file_reachable_for_code_splitting— for CSS files, follow the dependencies of live parts only (previously followed none), so the runtime's__commonJSgets the entry bit exactly when the printed stub uses it, without dragging__exportinto every chunk that links a stylesheet.src/bundler/linker_context/scanImportsAndExports.rs:DependencyWrapper::wrapgains acss_astsfield and, when wrapping a CSS file, does not descend into its import records (@import,url(),composes) since the JS stub evaluates nothing from them.test/bundler/css/css-modules.test.ts: four newitBundledtests, each withrun:output verification and inline snapshots of the emitted JS.
Security risks
None. This is bundler output-shape logic — no auth, crypto, syscalls, or untrusted-input parsing.
Level of scrutiny
High. Tree shaking (mark_file_live_step) and reachability (mark_file_reachable_for_code_splitting) are the core of the linker; a wrong liveness bit either drops needed code or bloats every chunk. The changes are small (~30 native lines) and each is guarded to CSS files specifically, but the interaction between the three (wrap-kind gate, live-parts gate, wrap-propagation skip) is subtle enough to merit a maintainer's read.
Other factors
- The PR description is exceptionally thorough: root-cause traced to specific lines, mechanism explained via the lazy-export / parts / entry-bits background, and 15+ bundler test suites listed as unchanged.
- Explicit overlap with #38286 on
mark_file_reachable_for_code_splitting— that PR removes thecontinueunconditionally, this one gates on part liveness.RequireCssInOneEntryDoesNotAddRuntimeToOthershere is stated to be the test that #38286's approach would fail. A human should coordinate merge order. - I checked the borrow discipline for the new
self.graph.parts_liveread insidemark_file_reachable_for_code_splitting: the outer&mut *parts_livereborrow (line 884) is moved intoTreeShakeCtxand dropped at the end of that block (line 909) before the code-splitting loop begins, so there is no live aliasing&mutwhen the new code reads it via&mut self. - The
DependencyWrapperchange adds a sixth field to theunsafeblock that groups thesplit_raw()derefs; the SAFETY comment count was updated (five → six). - No prior human review comments; CI is still building.
|
#38286 now carries the same live-parts rule in // Of the JS parts a stylesheet also carries, only the live ones get printed.
let live_parts_only = ctx.css_reprs[source_index as usize].is_some();
let parts_live = &self.graph.parts_live[source_index as usize];
let parts = ctx.parts[source_index as usize].as_slice();
for (part_index, part) in parts.iter().enumerate() {
if live_parts_only && !parts_live.is_set(part_index) {
continue;
}
for dependency in part.dependencies.iter() {(replacing the |
Following a CSS file's live parts from a traversal rooted at a stylesheet entry point (an explicit one, or an import()ed stylesheet under splitting) gave the runtime an entry bit that corresponds to no JS chunk, which under --splitting split the runtime away from the chunk printing the stylesheet's wrapper or namespace object. Skip the parts when the root is a stylesheet, and spell the live-parts filter the way #38286 does.
| // A stylesheet entry point only gets a CSS chunk (`compute_chunks`), so | ||
| // its bit must not reach the runtime through the JS parts of the | ||
| // stylesheets it reaches: under `--splitting` that bit would move the | ||
| // runtime out of the chunks that print those parts. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| // The JS printed for a stylesheet lives in this same source index. | ||
| // ESM importers reach its export parts through part dependencies, | ||
| // but when it is require()d (or import()ed without splitting) | ||
| // `generate_code_for_lazy_export` leaves a `module.exports = ...` | ||
| // part here that nothing depends on. Keep it the way the parts of | ||
| // every other CommonJS-wrapped file are kept: by walking the file. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| // The import records of a CSS file (`@import`, `url()`, `composes`) | ||
| // belong to its stylesheet, not to the JS stub that gets wrapped | ||
| // here; the stub evaluates nothing from them. Wrapping them would | ||
| // only emit empty `init_*` closures for the referenced files. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes tree-shaking liveness and entry-bit reachability in the linker — and the author has already flagged that merge order with #38286 needs a human call — a maintainer look is still worthwhile.
What was reviewed:
parts_liveis fully populated by the tree-shaking loop beforemark_file_reachable_for_code_splittingreads it, so the new live-parts gate is well-defined.from_css_entry_pointis captured from the outer entry-point argument before the BFS queue loop, so it correctly reflects the entry, not the visited file; non-CSS files reached from a CSS entry keep their pre-PR behavior (all parts followed).- Stopping
DependencyWrapper::wrapat CSS import records: a CSS file's@import/url()/composestargets are stylesheet-side; the JS stub evaluates nothing from them, so not wrapping them cannot drop an evaluation. - The three comment-cop flags look like false positives to me — the comments explain a non-obvious "why" (chunk-bit propagation, lazy-export part liveness), not a workaround.
Extended reasoning...
Overview
The PR fixes require('./x.module.css') (and import() without splitting) bundling to an empty __commonJS(function(exports, module) {}) wrapper, losing the class map and, when nothing else pulls in the runtime, throwing ReferenceError: __commonJS is not defined. Three targeted changes in the linker:
mark_file_live_step(src/bundler/LinkerContext.rs): a CSS file withwrap == Cjsnow falls through to the normal parts walk after following its CSS import records, so itsmodule.exports = ...lazy-export part is marked live.mark_file_reachable_for_code_splitting: for CSS files, follow dependencies of live parts only (previously all parts were skipped), gated so a CSS entry point does not propagate its bit through JS parts.DependencyWrapper::wrap(src/bundler/linker_context/scanImportsAndExports.rs): no longer descends into a CSS file's import records, sourl()/@import/composestargets are not spuriously wrapped.
Six new itBundled tests in test/bundler/css/css-modules.test.ts cover require, dynamic import without splitting, multi-entry runtime isolation, CSS-as-entry with splitting, CJS format, and stylesheet-dependency non-wrapping. Each asserts both a snapshot of the emitted JS and runtime stdout.
Security risks
None. This is bundler output-shaping logic; no untrusted input parsing, no filesystem writes outside the existing bundler paths, no auth/crypto surface.
Level of scrutiny
High. mark_file_live_step and mark_file_reachable_for_code_splitting are the two passes that decide what code is emitted and which chunk it lands in; a wrong gate here can silently drop code or move the runtime into the wrong chunk under --splitting. The change is small and the reasoning in the PR body is thorough, but the from_css_entry_point guard was added in a follow-up commit (c482c44) after the initial change — the kind of subtle interaction that benefits from a bundler maintainer's eye. I verified the ordering invariant (parts_live is written by the tree-shaking loop at ~L907 and only read by the reachability loop at ~L939) and that the from_css_entry_point capture happens outside the BFS loop so it names the entry, not the visited file.
Other factors
- The author ran the full bundler suite (907 tests, 0 failures) and CI is green (177/179 jobs passed, none failed at last update).
- The PR body and a follow-up comment explicitly note that this PR shares a hunk with #38286 and that merge order needs a human decision; the reachability hunk here differs from #38286's coordinated text by the extra
from_css_entry_pointterm, so whichever lands second will need a manual merge of that line. - Three comment-cop bot flags on the new code comments are, in my reading, false positives: the comments explain why the gate exists (chunk-bit propagation under splitting; lazy-export part unreached by dependencies), which is exactly the non-local "why" that would otherwise take several tool calls to reconstruct. They are not justifying a workaround.
- No CODEOWNERS entry covers
src/bundler/.
|
Closing this PR because it has been inactive for more than 90 days. |
Problem
require("./x.module.css"), andimport("./x.module.css")without--splitting, bundle the CSS file tovar require_x_module = __commonJS(function(exports, module) {});, so it evaluates to{}and the class map is lost. Plain.cssgets the same empty wrapper.import x fromandimport * asare fine.__commonJSand throwsReferenceError: __commonJS is not definedwhen loaded.generate_code_for_lazy_export(src/bundler/linker_context/generateCodeForLazyExport.rs:377) rewrites the CSS file's lazy-export part intomodule.exports = {...}. Nothing depends on that part, andmark_file_live_step(src/bundler/LinkerContext.rs:2730) returned from its CSS branch before the walk that keeps the non-removable parts of every other live file, so the part was never live andgenerate_code_for_file_in_chunk_jsskipped it.__commonJS:mark_file_reachable_for_code_splitting(src/bundler/LinkerContext.rs:2653) likewisecontinued for CSS files before following part dependencies. The wrapper part's dependency on the runtime's__commonJSpart therefore never gave the runtime the entry point's bit, and the runtime was left out of the chunk.scan_imports_and_exports(DependencyWrapper::wrap), into the stylesheet's own import records. An asset referenced byurl()from a required stylesheet came out asvar init_img = () => {};plus the__esmhelper, and a JS import of the same asset gained aninit_img()call.Fix
mark_file_live_step: a CSS file whose wrap kind isCjsfalls through to the normal parts walk after following its CSS import records. The lazy-export part is the wrapper's body, and this is exactly how the parts of every other CommonJS-wrapped file (JSON, TOML,.cjs) are kept. ESM-imported CSS files are unchanged: their exports are reached through part dependencies, and the gate also leaves--format internal_bake_devoutput as it is.mark_file_reachable_for_code_splitting: for a CSS file, follow the dependencies of its live parts. The live parts are precisely what gets printed for the file, so the runtime is reached exactly when the chunk prints something that uses it (the CommonJS wrapper here, or the__exportnamespace object of a namespace import). Following every part, as is done for JS files, would pull the runtime into every chunk that links a stylesheet, because every ESM-imported CSS stub has a namespace-export part depending on__export; that is what failstest/bundler/html-import-manifest.test.tson bundler: pull the runtime into chunks that print a CSS file's namespace object #38286, which removes thecontinueunconditionally, andRequireCssInOneEntryDoesNotAddRuntimeToOthersbelow pins it.DependencyWrapper::wrap: wrapping a CSS file no longer descends into its import records. The stub evaluates nothing from its@import/url()/composestargets (composed class names are printed as strings at bundle time), so wrapping them only produced the empty closures above. esbuild's stub for a CSS file has no import records at all.bun bd test test/bundler/css/css-modules.test.ts: four new tests, each failing on the released build ({}output, theReferenceError, snapshots containing the empty wrapper andinit_img), passing with the fix.bundler_loader,bundler_splitting,html-import-manifest,bundler_html,bundler_html_server,metafile,bundler_edgecase,bundler_cjs,bundler_cjs2esm,bun-build-api,bundler_regressions,bundler_defer,bundler_bun,bundler_compile_splitting, and the esbuildcss,loader,splitting,default,dce,importstar,metafilesuites (907 tests, 0 failures).cargo clippy -p bun_bundleris clean.--splittingis not part of this PR. With this PR the namespace-import case works without--splittingas well.--splittingcombined withrequire()orimport()of a CSS file is a separate, pre-existing problem (cross-chunk imports and CSS dynamic-import entry points) that this PR does not address.Background
to_lazy_export_ast) whose part 1 holds a singleSLazyExportexpression, andgenerate_code_for_lazy_exportlater turns it into eithermodule.exports = expr(when the file ends up CommonJS, i.e. it wasrequire()d) or generatedexportparts. For CSS the expression is the class-name map ({}for plain CSS), and the same source index also carries the stylesheet. esbuild gives this stub its own source index, which is where the CSS special cases in these passes come from.mark_file_live_step) marks a live file's non-removable parts live and follows part dependencies; only live parts are printed. The CommonJS wrappervar require_x = __commonJS(...)is a synthesized part that importers depend on, and its body is the file's other live parts.mark_file_reachable_for_code_splittingrecords which entry points reach each file through import records and part dependencies. A file's live parts are printed into a chunk only if the file carries that chunk's entry bit; this is how the runtime module (__commonJS,__export, ...) gets into a chunk.scan_imports_and_exportswraps the files it imports too, so that they are evaluated lazily together with it.Repro and output
Before:
(With an entry point that does reach the runtime for another reason, it runs and prints
{}.)After:
Output of
require("./a.css")wherea.csscontainsurl(./img.png), before (the__esmline and theimg.pngblock are gone after):