Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
0302341
dev server: ship a CSS module's class-name map as an HMR module
robobun Sep 8, 2026
33c8ea8
dev server: bundle a stylesheet again when a module imports one that …
robobun Sep 8, 2026
d53ee8d
trim comments
robobun Sep 8, 2026
5384e16
test(bake): cover a shared css module instance, an emptied css module…
robobun Sep 8, 2026
13c2910
dev server: give a disabled import with bindings an empty namespace
robobun Sep 9, 2026
81136b2
trim comment
robobun Sep 9, 2026
4444089
Merge branch 'main' into robobun/e0e15596/dev-server-css-modules
robobun Nov 6, 2026
906d532
dev server: report a bad `composes` as a build error, and drop the cl…
robobun Nov 6, 2026
4b4088b
trim comment
robobun Nov 6, 2026
2ba6c98
dev server: keep the edges of a CSS module that fails on `composes`, …
robobun Nov 6, 2026
33d17ff
dev server: keep the last good stylesheet when a CSS module fails on …
robobun Nov 6, 2026
f863271
bundler: a CSS module links to its class-name module in every graph o…
robobun Nov 6, 2026
9f9463e
dev server: a CSS module is a module in every graph that imports it
robobun Nov 6, 2026
5d556f4
test: a file that an onResolve plugin declines is a module of each graph
robobun Nov 6, 2026
efef93d
bundler: free a server component parse task after it ran
robobun Nov 6, 2026
2101276
trim comments
robobun Nov 6, 2026
7591d39
bundler: own the server component task box while its callback runs
robobun Nov 6, 2026
d490d29
dev server: write the server record of each stylesheet copy that a se…
robobun Nov 6, 2026
ea73c4c
Revert "dev server: write the server record of each stylesheet copy t…
robobun Nov 7, 2026
78929be
dev server: drop the ES view of a CommonJS module after its wrapper ran
robobun Nov 7, 2026
dfb3392
dev server: queue the server copies of a CSS module in the invalidate…
robobun Nov 7, 2026
1338901
dev server: bind the empty module only for the import of a stylesheet
robobun Nov 7, 2026
50ada1e
dev server: give the link of a bundle an AST scope
robobun Nov 7, 2026
1c5811b
dev server: fail a CSS module with an invalid import in the graph of …
robobun Nov 7, 2026
e41a41b
dev server: run the cross-file `composes` checks of the link step
robobun Nov 7, 2026
93cd173
bundler: say why a production build keeps the `ssr:` prefix in CSS mo…
robobun Nov 7, 2026
53d54be
test: dev server CSS modules with a page open, in each graph, and on …
robobun Nov 7, 2026
6838126
trim comments
robobun Nov 7, 2026
f276138
dev server: decide at the link which graph records the failure of a s…
robobun Nov 7, 2026
8590608
dev server: do not record a failure for the unused copy of a plain st…
robobun Nov 7, 2026
d7355e9
test: a failed stylesheet that only stylesheets import, under a serve…
robobun Nov 7, 2026
d9b8325
dev server: keep a failed stylesheet that stylesheets import a css child
robobun Nov 7, 2026
ca4ce86
dev server: give a file its stale bit when its chunk is received
robobun Nov 7, 2026
faef438
test: check the error of the route before the fix of the stylesheet
robobun Nov 7, 2026
192d5bc
dev server: leave the server record of a plain stylesheet when an imp…
robobun Nov 7, 2026
9328360
trim a comment
robobun Nov 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,10 @@ impl<'a> LinkerContext<'a> {
// has finished pushing wrapper / entry-point parts.
{
let loaders = self.parse_graph().input_files.items_loader();
let sources = self.parse_graph().input_files.items_source();
let targets = self.graph.ast.items_target();
let is_bake_dev =
self.options.output_format == crate::options::OutputFormat::InternalBakeDev;
let parts_col = self.graph.ast.items_parts();
let mut parts_live: Vec<bun_collections::AutoBitSet> =
Vec::with_capacity(parts_col.len());
Expand All @@ -942,6 +946,14 @@ impl<'a> LinkerContext<'a> {
if loaders.get(i).is_some_and(|l| *l == Loader::Html) && parts.len() > 1 {
bits.set(1);
}
// Likewise for a client CSS module's stub: the dev format links imports at runtime.
if is_bake_dev
&& parts.len() > 1
&& loaders.get(i).is_some_and(|l| l.is_css())
&& crate::is_client_css_module(targets[i], sources[i].path.pretty)
{
bits.set(1);
}
parts_live.push(bits);
}
self.graph.parts_live = parts_live;
Expand Down Expand Up @@ -4963,6 +4975,18 @@ impl<'a> LinkerContext<'a> {
)
}

/// See `linker_context/generateCodeForLazyExport.rs`.
#[inline]
pub(crate) fn populate_css_module_lazy_export(
&mut self,
source_index: crate::IndexInt,
) -> Result<(), AllocError> {
crate::linker_context::generate_code_for_lazy_export::populate_css_module_lazy_export(
self,
source_index,
)
}

/// Synthesizes a named export symbol in a file (creating a new part for
/// it) and returns the symbol's `Ref` and the part index.
pub(crate) fn generate_named_export_in_file(
Expand Down
5 changes: 1 addition & 4 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,10 +1266,7 @@ pub mod parse_worker {
// `temp_log` is flushed into `log` on every exit path via linear
// control flow (scopeguard would alias `log`/`temp_log`).

const CSS_MODULE_SUFFIX: &[u8] = b".module.css";
let enable_css_modules = source.path.pretty.len() > CSS_MODULE_SUFFIX.len()
&& &source.path.pretty[source.path.pretty.len() - CSS_MODULE_SUFFIX.len()..]
== CSS_MODULE_SUFFIX;
let enable_css_modules = crate::is_css_module_path(source.path.pretty);
// `parse_bundler` takes `ParserOptions<'static>` (the
// `'a` on `ParserOptions` is PhantomData-only; storage is a raw
// `NonNull<Log>`). Construct via `default(None)` to get `'static`,
Expand Down
26 changes: 26 additions & 0 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,10 @@ pub mod bv2_impl {
Unknown = 0,
Js = 1,
Asset = 2,
/// A stylesheet the page loads through a `<link>` tag; a JS import of it binds nothing.
Css = 3,
/// A stylesheet plus an HMR module, keyed by the file's path, that exports its class names.
CssModule = 4,
}
#[derive(Copy, Clone)]
pub struct CacheEntry {
Expand Down Expand Up @@ -5510,6 +5513,7 @@ pub mod bv2_impl {

self.dynamic_import_entry_points = ArrayHashMap::new();
let mut html_files: ArrayHashMap<Index, ()> = ArrayHashMap::new();
let mut css_module_stubs: Vec<Index> = Vec::new();

// Separate non-failing files into two lists: JS and CSS
let js_reachable_files: &[Index] = 'reachable_files: {
Expand Down Expand Up @@ -5657,6 +5661,22 @@ pub mod bv2_impl {
}
}

// A client CSS module also ships a module with its class-name map in the JS chunk.
for entry_point in start.css_entry_points.keys() {
let idx = entry_point.get() as usize;
// SAFETY: `idx < ast.len()`; see the column aliasing note above.
let part_count = unsafe { (*parts_col.add(idx)).len() };
if part_count > 1
&& crate::is_client_css_module(
asts.items_target()[idx],
sources[idx].path.pretty,
)
{
js_files.push(*entry_point);
css_module_stubs.push(*entry_point);
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved

// SAFETY: `alloc_slice_copy` returns into the bundler arena which outlives
// this function. Erase the `&self` lifetime via `*const` so the borrow on
// `self.arena()` does not extend across the `&mut self` calls below
Expand Down Expand Up @@ -5698,6 +5718,12 @@ pub mod bv2_impl {
.map_err(|_| AllocError)?;
}

// This pipeline skips `generate_code_for_lazy_export`, so fill the class-name maps here.
for source_index in &css_module_stubs {
self.linker
.populate_css_module_lazy_export(source_index.get())?;
}
Comment thread
robobun marked this conversation as resolved.
Resolved

// HMR skips tree-shaking, so size and seed the part-liveness bitsets
// here: every part of every JS file is considered live.
{
Expand Down
1 change: 1 addition & 0 deletions src/bundler/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub(crate) use bun_ast::UseDirective;
pub(crate) use bun_ast::{Part, Ref};
pub use bun_js_printer::MangledProps;
pub use options_impl::PathTemplate;
pub(crate) use options_impl::{is_client_css_module, is_css_module_path};

pub use HTMLImportManifest::html_import_manifest;
pub use bun_core::cheap_prefix_normalizer;
Expand Down
40 changes: 27 additions & 13 deletions src/bundler/linker_context/convertStmtsForChunkForDevServer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,33 @@ pub(crate) fn convert_stmts_for_chunk_for_dev_server<'bump>(
let input_files = &c.parse_graph().input_files;
let loaders = input_files.items_loader();
let sources = input_files.items_source();
for record in ast.import_records.as_mut_slice() {
if record.path.is_disabled {
continue;
}
if record.source_index.is_valid()
&& loaders[record.source_index.get() as usize] == Loader::Css
{
record.path.is_disabled = true;
continue;
}
// Make sure the printer gets the resolved path
if record.source_index.is_valid() {
record.path = sources[record.source_index.get() as usize].path;
// A CSS file's own records belong to the CSS chunk (another thread); its stub imports nothing.
if ast.css.is_none() {
let targets = c.graph.ast.items_target();
for record in ast.import_records.as_mut_slice() {
if record.path.is_disabled {
continue;
}
if record.source_index.is_valid() {
let imported = record.source_index.get() as usize;
let is_css = loaders[imported] == Loader::Css;
// A plain stylesheet reaches the page through a <link> tag, not the module registry.
if is_css
&& !crate::is_client_css_module(
targets[imported],
sources[imported].path.pretty,
)
Comment thread
robobun marked this conversation as resolved.
Resolved
{
record.path.is_disabled = true;
continue;
}
// Make sure the printer gets the resolved path
record.path = sources[imported].path;
// A CSS module's class-name map is a registry module; link it at runtime like JS.
if is_css {
record.source_index = bun_ast::Index::INVALID;
}
}
}
}

Expand Down
49 changes: 30 additions & 19 deletions src/bundler/linker_context/generateCodeForLazyExport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,13 @@ use bun_collections::DynamicBitSetUnmanaged as BitSet;

type SymbolList<'a> = bun_ast::symbol::List<'a>;

pub(crate) fn generate_code_for_lazy_export(
/// Fills a CSS file's lazy-export object with its class-name map. A no-op for other lazy exports.
pub(crate) fn populate_css_module_lazy_export(
this: &mut LinkerContext,
source_index: IndexInt,
) -> Result<(), AllocError> {
let mut exports_kind = this.graph.ast.items_exports_kind()[source_index as usize];
// The dev server's module format represents lazy-export modules (JSON,
// TOML, CSS modules, ...) as CommonJS modules evaluated by the HMR
// runtime, so always generate the `module.exports = ...` form below.
// The ESM form would synthesize `export` parts that
// `print_dev_server_module` cannot represent.
if this.options.output_format == crate::options::OutputFormat::InternalBakeDev
&& exports_kind != bun_ast::ExportsKind::Cjs
{
exports_kind = bun_ast::ExportsKind::Cjs;
this.graph.ast.items_exports_kind_mut()[source_index as usize] = exports_kind;
}
// Take `parts` as a raw pointer *before* the
// long-lived immutable `items_css()` borrow below; re-borrowed again later as needed.
// long-lived immutable `items_css()` borrow below.
let parts: *mut [Part] = this.graph.ast.items_parts_mut()[source_index as usize].as_mut_slice();
// SAFETY: parse_graph backref; raw deref because `all_sources` is held
// across `&mut *this.log` below (split borrow).
Expand All @@ -44,20 +33,18 @@ pub(crate) fn generate_code_for_lazy_export(
let maybe_css_ast: Option<&BundlerStyleSheet> = all_css_asts[source_index as usize].as_deref();

// SAFETY: `parts` is a stable SoA column slice valid for the link pass.
if unsafe { (&*parts).len() } < 1 {
panic!("Internal error: expected at least one part for lazy export");
if unsafe { (&*parts).len() } < 2 {
panic!("Internal error: expected a lazy export part");
}

// SAFETY: `parts.ptr[1]` — Vec raw indexing; using index 1 here.
// SAFETY: index 1 is in bounds (checked above).
let part: &mut Part = unsafe { &mut (*parts)[1] };

// `Part.stmts: StoreSlice<Stmt>` — safe `Deref` to `&[Stmt]`.
if part.stmts.is_empty() {
panic!("Internal error: expected at least one statement in the lazy export");
}

let module_ref = this.graph.ast.items_module_ref()[source_index as usize];

// Handle css modules
//
// --- original comment from esbuild ---
Expand Down Expand Up @@ -363,6 +350,30 @@ pub(crate) fn generate_code_for_lazy_export(
}
}
}
Ok(())
}

pub(crate) fn generate_code_for_lazy_export(
this: &mut LinkerContext,
source_index: IndexInt,
) -> Result<(), AllocError> {
let mut exports_kind = this.graph.ast.items_exports_kind()[source_index as usize];
// `print_dev_server_module` only has a CommonJS form (`module.exports = ...`) for lazy exports.
if this.options.output_format == crate::options::OutputFormat::InternalBakeDev
&& exports_kind != bun_ast::ExportsKind::Cjs
{
exports_kind = bun_ast::ExportsKind::Cjs;
this.graph.ast.items_exports_kind_mut()[source_index as usize] = exports_kind;
}

populate_css_module_lazy_export(this, source_index)?;

let parts: *mut [Part] = this.graph.ast.items_parts_mut()[source_index as usize].as_mut_slice();
// SAFETY: stable SoA column slice valid for the link pass; index 1 was
// bounds-checked by `populate_css_module_lazy_export`.
let part: &mut Part = unsafe { &mut (*parts)[1] };

let module_ref = this.graph.ast.items_module_ref()[source_index as usize];

let stmt: Stmt = part.stmts[0];
let StmtData::SLazyExport(lazy) = stmt.data else {
Expand Down
11 changes: 11 additions & 0 deletions src/bundler/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,17 @@ pub(crate) fn is_node_builtin(str: &[u8]) -> bool {
bun_resolve_builtins::Alias::has(str, bun_ast::Target::Node, Default::default())
}

/// Whether the CSS parser enables CSS modules for this path.
pub(crate) fn is_css_module_path(pretty_path: &[u8]) -> bool {
const CSS_MODULE_SUFFIX: &[u8] = b".module.css";
pretty_path.len() > CSS_MODULE_SUFFIX.len() && pretty_path.ends_with(CSS_MODULE_SUFFIX)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// A CSS module whose class-name map the dev server ships to the browser as an HMR module.
pub(crate) fn is_client_css_module(target: Target, pretty_path: &[u8]) -> bool {
target == Target::Browser && is_css_module_path(pretty_path)
}

const DEFAULT_WILDCARD_PATTERNS: &[(&[u8], &[u8])] = &[
(b"/bun:", b""),
// (b"/src:", b""),
Expand Down
7 changes: 1 addition & 6 deletions src/bundler/transpiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3160,12 +3160,7 @@ impl<'a> Transpiler<'a> {
// this arm, before any other `log_mut()` reborrow above.
let mut opts = bun_css::ParserOptions::default(None);
opts.logger = Some(core::ptr::NonNull::new(self.log).unwrap());
const CSS_MODULE_SUFFIX: &[u8] = b".module.css";
let enable_css_modules = file_path_text.len() > CSS_MODULE_SUFFIX.len()
&& strings::eql_comptime(
&file_path_text[file_path_text.len() - CSS_MODULE_SUFFIX.len()..],
CSS_MODULE_SUFFIX,
);
let enable_css_modules = crate::is_css_module_path(file_path_text);
if enable_css_modules {
opts.filename = bun_paths::basename(file_path_text);
opts.css_modules = Some(bun_css::CssModuleConfig::default());
Expand Down
22 changes: 11 additions & 11 deletions src/runtime/bake/DevServer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4167,6 +4167,10 @@ pub(super) fn finalize_bundle(
// changed file, removing dependencies. This pass also flags what routes
// have been modified.
for part_range in js_chunk.content.javascript().parts_in_chunk_in_order.iter() {
// A CSS module's stub: its records are the stylesheet's, which the CSS loop below handles.
if input_file_loaders[part_range.source_index.get() as usize].is_css() {
continue;
}
match targets[part_range.source_index.get() as usize].bake_graph() {
bake::Graph::Server | bake::Graph::Ssr => dev.server_graph.process_chunk_dependencies(
&mut ctx,
Expand Down Expand Up @@ -5062,10 +5066,7 @@ impl DevServer {
}
}

#[derive(Copy, Clone)]
pub struct CacheEntry {
pub(crate) kind: FileKind,
}
pub use bun_bundler::bake_types::CacheEntry;

impl DevServer {
pub(crate) fn is_file_cached(&mut self, path: &[u8], side: bake::Graph) -> Option<CacheEntry> {
Expand All @@ -5081,13 +5082,12 @@ impl DevServer {
let g = $g;
let index = g.bundled_files.get_index(path)?;
if !g.stale_files.is_set(index) {
return Some(CacheEntry {
kind: g
.get_file_by_index(incremental_graph::FileIndex::init(
u32::try_from(index).expect("int cast"),
))
.file_kind(),
});
return g
.get_file_by_index(incremental_graph::FileIndex::init(
u32::try_from(index).expect("int cast"),
))
.cache_kind()
.map(|kind| CacheEntry { kind });
}
return None;
}};
Expand Down
Loading
Loading