Skip to content

bundler: emit the module.exports body of a require()d CSS file - #38307

Closed
robobun wants to merge 2 commits into
mainfrom
farm/fa1c91ca/css-require-lazy-export-live
Closed

robobun wants to merge 2 commits into
mainfrom
farm/fa1c91ca/css-require-lazy-export-live

Conversation

@robobun

@robobun robobun commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • require("./x.module.css"), and import("./x.module.css") without --splitting, bundle the CSS file to var require_x_module = __commonJS(function(exports, module) {});, so it evaluates to {} and the class map is lost. Plain .css gets the same empty wrapper. import x from and import * as are fine.
  • When nothing else in the bundle uses the runtime (for example an entry point without exports), the output also lacks the definition of __commonJS and throws ReferenceError: __commonJS is not defined when loaded.
  • Cause of the empty body: for a CommonJS-wrapped file, generate_code_for_lazy_export (src/bundler/linker_context/generateCodeForLazyExport.rs:377) rewrites the CSS file's lazy-export part into module.exports = {...}. Nothing depends on that part, and mark_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 and generate_code_for_file_in_chunk_js skipped it.
  • Cause of the missing __commonJS: mark_file_reachable_for_code_splitting (src/bundler/LinkerContext.rs:2653) likewise continued for CSS files before following part dependencies. The wrapper part's dependency on the runtime's __commonJS part therefore never gave the runtime the entry point's bit, and the runtime was left out of the chunk.
  • Related: wrapping a CSS file also propagated, in step 2 of scan_imports_and_exports (DependencyWrapper::wrap), into the stylesheet's own import records. An asset referenced by url() from a required stylesheet came out as var init_img = () => {}; plus the __esm helper, and a JS import of the same asset gained an init_img() call.

Fix

  • mark_file_live_step: a CSS file whose wrap kind is Cjs falls 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_dev output 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 __export namespace 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 fails test/bundler/html-import-manifest.test.ts on bundler: pull the runtime into chunks that print a CSS file's namespace object #38286, which removes the continue unconditionally, and RequireCssInOneEntryDoesNotAddRuntimeToOthers below pins it.
  • DependencyWrapper::wrap: wrapping a CSS file no longer descends into its import records. The stub evaluates nothing from its @import / url() / composes targets (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.
  • Verified with bun bd test test/bundler/css/css-modules.test.ts: four new tests, each failing on the released build ({} output, the ReferenceError, snapshots containing the empty wrapper and init_img), passing with the fix.
  • Also run, unchanged: 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 esbuild css, loader, splitting, default, dce, importstar, metafile suites (907 tests, 0 failures). cargo clippy -p bun_bundler is clean.
  • Relationship to bundler: pull the runtime into chunks that print a CSS file's namespace object #38286 (namespace import of a CSS file): its reachability hunk is the unconditional form of the one here, so the two touch the same lines; its cross-chunk change for --splitting is not part of this PR. With this PR the namespace-import case works without --splitting as well. --splitting combined with require() or import() 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

  • Lazy export: loaders such as JSON, TOML and CSS do not parse to JS. The parser builds a two-part JS AST for them (to_lazy_export_ast) whose part 1 holds a single SLazyExport expression, and generate_code_for_lazy_export later turns it into either module.exports = expr (when the file ends up CommonJS, i.e. it was require()d) or generated export parts. 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.
  • Parts and liveness: every file is split into parts. Tree shaking (mark_file_live_step) marks a live file's non-removable parts live and follows part dependencies; only live parts are printed. The CommonJS wrapper var require_x = __commonJS(...) is a synthesized part that importers depend on, and its body is the file's other live parts.
  • Entry bits: after tree shaking, mark_file_reachable_for_code_splitting records 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.
  • Wrapping propagation: when a file gets wrapped, step 2 of scan_imports_and_exports wraps the files it imports too, so that they are evaluated lazily together with it.
Repro and output
printf '.foo { color: blue }\n' > style.module.css
printf 'const s = require("./style.module.css");\nconsole.log(JSON.stringify(s));\nexport {};\n' > entry.ts
bun build entry.ts --outdir out && bun out/entry.js

Before:

// style.module.css
var require_style_module = __commonJS(function(exports, module) {});

// entry.ts
var s = require_style_module();
console.log(JSON.stringify(s));
ReferenceError: __commonJS is not defined

(With an entry point that does reach the runtime for another reason, it runs and prints {}.)

After:

var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);

// style.module.css
var require_style_module = __commonJS(function(exports, module) {
  module.exports = {
    foo: "foo_Hg8gNQ"
  };
});

// entry.ts
var s = require_style_module();
console.log(JSON.stringify(s));
{"foo":"foo_Hg8gNQ"}

Output of require("./a.css") where a.css contains url(./img.png), before (the __esm line and the img.png block are gone after):

var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);

// a.css
var require_a = __commonJS(function(exports, module) {});

// img.png
var init_img = () => {};

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.
@robobun

robobun commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:05 AM PT - Aug 14th, 2026

❌ @robobun, your commit c482c44 has some failures in Build #95700 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 38307

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

bun-38307 --bun

@robobun

robobun commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

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: bun build of an entry that does require("./style.module.css") prints an empty __commonJS(function(exports, module) {}) wrapper for the CSS file (so require() returns {}), and when nothing else in the bundle uses the runtime the output also throws ReferenceError: __commonJS is not defined. Tests: the four new cases in test/bundler/css/css-modules.test.ts fail on the released build and pass with this branch.

@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8037bf2b-e7ff-4bde-b616-64409383b278

📥 Commits

Reviewing files that changed from the base of the PR and between b8efb12 and c482c44.

📒 Files selected for processing (2)
  • src/bundler/LinkerContext.rs
  • test/bundler/css/css-modules.test.ts

Walkthrough

Changes

The 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

Layer / File(s) Summary
Exclude CSS from JS wrapper propagation
src/bundler/linker_context/scanImportsAndExports.rs
DependencyWrapper now accesses CSS AST entries and stops traversal for CSS files.
Traverse live CSS dependencies
src/bundler/LinkerContext.rs
Code splitting follows dependencies from live CSS parts. Tree shaking preserves CSS CommonJS wrapper parts.
Validate CSS CommonJS output
test/bundler/css/css-modules.test.ts
Tests cover CommonJS require(), dynamic imports, multiple entries, runtime isolation, emitted CSS, and stylesheet dependencies.

Suggested reviewers: jarred-sumner, dylan-conway

Merge Risk: ⚪ Minimal · up to c482c

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)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: emitting the module.exports body for CSS files loaded with require().
Description check ✅ Passed The description explains the problem, fix, scope, verification steps, test results, and related work in sufficient detail.
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.

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

@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 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: verified parts_live is populated (tree shaking runs first, line 907 before line 939) and the outer &mut parts_live reborrow is consumed by TreeShakeCtx before this reads it via self.
  • mark_file_live_step: the WrapKind::Cjs gate falls through to the normal parts walk; the HTML branch below it doesn't fire for CSS, and internal_bake_dev never sets Cjs on CSS so it's unaffected as claimed.
  • DependencyWrapper::wrap: the CSS-file guard sits after did_wrap_dependencies/wrap are set, so the CSS stub itself is still wrapped — only the descent into @import/url()/composes records 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 with WrapKind::Cjs falls through to the normal parts walk after following its stylesheet import records, so the module.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 __commonJS gets the entry bit exactly when the printed stub uses it, without dragging __export into every chunk that links a stylesheet.
  • src/bundler/linker_context/scanImportsAndExports.rs: DependencyWrapper::wrap gains a css_asts field 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 new itBundled tests, each with run: 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 the continue unconditionally, this one gates on part liveness. RequireCssInOneEntryDoesNotAddRuntimeToOthers here 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_live read inside mark_file_reachable_for_code_splitting: the outer &mut *parts_live reborrow (line 884) is moved into TreeShakeCtx and dropped at the end of that block (line 909) before the code-splitting loop begins, so there is no live aliasing &mut when the new code reads it via &mut self.
  • The DependencyWrapper change adds a sixth field to the unsafe block that groups the split_raw() derefs; the SAFETY comment count was updated (five → six).
  • No prior human review comments; CI is still building.

@robobun

robobun commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator Author

#38286 now carries the same live-parts rule in mark_file_reachable_for_code_splitting (since 20868a0; test/bundler/html-import-manifest.test.ts passes there again). Both PRs need this hunk, so to let them merge in either order without a conflict, #38286 (the earlier PR) keeps it frozen as below; if this PR uses the identical text, git merges the second one cleanly:

            // 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 // CSS files only follow their import records. block through the old for part in ... line; everything below is unchanged.) The mark_file_live_step and DependencyWrapper::wrap changes here do not overlap with #38286, and the cross-chunk change in #38286 is not needed for require().

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.
Comment on lines +2622 to +2625
// 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.

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

Comment on lines +2747 to +2752
// 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.

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

Comment on lines +1224 to +1227
// 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.

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.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

@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 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_live is fully populated by the tree-shaking loop before mark_file_reachable_for_code_splitting reads it, so the new live-parts gate is well-defined.
  • from_css_entry_point is 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::wrap at CSS import records: a CSS file's @import/url()/composes targets 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 with wrap == Cjs now falls through to the normal parts walk after following its CSS import records, so its module.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, so url()/@import/composes targets 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_point term, 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/.

@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

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.

1 participant