From ce2d1cd56eaf3aba61d8b50d67b5d0d17288ce65 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 3 Sep 2026 03:36:40 +0000 Subject: [PATCH 1/5] bundler: give each entry point its own chunk without --splitting Without code splitting, compute_chunks keyed each entry point's chunk by the full entry_bits of its file. Entry points that reach each other have the same entry_bits, so they shared one chunk and only the last one was written. CSS entry points hashed the same bits and had the same problem. Key both by the entry point's own bit, as code splitting already does. Each non-split chunk also visits its own entry point first when it orders its files. Distances are the minimum over all entry points, so another entry point in the chunk could sort first and run its imports too early. --- src/bundler/linker_context/computeChunks.rs | 30 +++-------- .../findAllImportedPartsInJSOrder.rs | 14 +++++ test/bundler/bundler_compile.test.ts | 20 ++++++++ test/bundler/bundler_edgecase.test.ts | 51 +++++++++++++++++++ 4 files changed, 93 insertions(+), 22 deletions(-) diff --git a/src/bundler/linker_context/computeChunks.rs b/src/bundler/linker_context/computeChunks.rs index d1ee44e492ec..b4b32f7ef68a 100644 --- a/src/bundler/linker_context/computeChunks.rs +++ b/src/bundler/linker_context/computeChunks.rs @@ -1,5 +1,4 @@ use crate::mal_prelude::*; -use bun_alloc::ArenaVecExt as _; use core::sync::atomic::AtomicUsize; use bun_alloc::Arena; // bumpalo::Bump re-export @@ -109,28 +108,16 @@ pub(crate) fn compute_chunks( let has_html_chunk = loaders[source_index as usize] == Loader::Html; - // For code splitting, entry point chunks should be keyed by ONLY the entry point's - // own bit, not the full entry_bits. This ensures that if an entry point file is - // reachable from other entry points (e.g., via re-exports), its content goes into - // a shared chunk rather than staying in the entry point's chunk. + // Entry point chunks are keyed by ONLY the entry point's own bit, not the full + // entry_bits. Entry points that reach each other have the same entry_bits, and + // each one still needs its own chunk. With code splitting, an entry point file + // that other entry points reach (e.g., via re-exports) goes into a shared chunk. // https://github.com/evanw/esbuild/blob/cd832972927f1f67b6d2cc895c06a8759c1cf309/internal/linker/linker.go#L3882 let mut entry_point_chunk_bits = AutoBitSet::init_empty(this.graph.entry_points.len())?; entry_point_chunk_bits.set(entry_bit as usize); - let js_chunk_key: &[u8] = 'brk: { - if code_splitting { - break 'brk temp - .alloc_slice_copy(entry_point_chunk_bits.bytes(this.graph.entry_points.len())); - } else { - // Force HTML chunks to always be generated, even if there's an identical JS file. - // Build the byte key directly since - // entry_bits is arbitrary bytes (not UTF-8) and cannot go through fmt::Display. - let mut v = bun_alloc::ArenaVec::new_in(temp); - v.push((!has_html_chunk) as u8); - v.extend_from_slice(entry_bits.bytes(this.graph.entry_points.len())); - break 'brk v.into_bump_slice(); - } - }; + let js_chunk_key: &[u8] = + temp.alloc_slice_copy(entry_point_chunk_bits.bytes(this.graph.entry_points.len())); // Put this early on in this loop so that CSS-only entry points work. if has_html_chunk { @@ -162,9 +149,7 @@ pub(crate) fn compute_chunks( // Create a chunk for the entry point here to ensure that the chunk is // always generated even if the resulting file is empty let hash_to_use = if !this.options.css_chunking { - bun_wyhash::hash( - temp.alloc_slice_copy(entry_bits.bytes(this.graph.entry_points.len())), - ) + bun_wyhash::hash(entry_point_chunk_bits.bytes(this.graph.entry_points.len())) } else { let mut hasher = Wyhash::init(5); bun_core::write_any_to_hasher(&mut hasher, order.len()); @@ -203,6 +188,7 @@ pub(crate) fn compute_chunks( // Create a chunk for the entry point here to ensure that the chunk is // always generated even if the resulting file is empty let js_chunk_entry = js_chunks.get_or_put(js_chunk_key)?; + debug_assert!(!js_chunk_entry.found_existing); entry_point_to_js_chunk_idx[entry_id_] = u32::try_from(js_chunk_entry.index).expect("int cast"); *js_chunk_entry.value_ptr = Chunk { diff --git a/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs b/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs index 8d7a8079dc69..f2e6df717b21 100644 --- a/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs +++ b/src/bundler/linker_context/findAllImportedPartsInJSOrder.rs @@ -106,6 +106,20 @@ pub(crate) fn find_imported_parts_in_js_order( Order::sort(&mut chunk_order_array); + // Without code splitting, a chunk holds every file that its entry point reaches. + // Distances are the minimum over all entry points, so other entry points in this + // chunk also sort at distance 0. Visit this chunk's own entry point first, so the + // files print in the order that this entry point imports them. + if !this.graph.code_splitting && chunk.entry_point.is_entry_point() { + let entry_point = chunk.entry_point.source_index(); + if let Some(i) = chunk_order_array + .iter() + .position(|order| order.source_index == entry_point) + { + chunk_order_array[..=i].rotate_right(1); + } + } + part_ranges_shared.clear(); parts_prefix_shared.clear(); diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index 307e53ffdebd..ac409393426c 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -401,6 +401,26 @@ describe("bundler", () => { }, }); } + // Two entry points that import() each other: the executable runs the first one. + itBundled("compile/EntryPointsImportEachOther", { + compile: true, + files: { + "/main.ts": /* js */ ` + import("./plugin.ts").then(plugin => console.log("main loaded", plugin.name)); + `, + "/plugin.ts": /* js */ ` + export const name = "plugin"; + export const loadMain = () => import("./main.ts"); + `, + }, + entryPointsRaw: ["./main.ts", "./plugin.ts"], + outfile: "dist/out", + run: { + stdout: "main loaded plugin", + file: "dist/out", + setCwd: true, + }, + }); // https://github.com/oven-sh/bun/issues/8697 itBundled("compile/EmbeddedFileOutfile", { compile: true, diff --git a/test/bundler/bundler_edgecase.test.ts b/test/bundler/bundler_edgecase.test.ts index 51777a28b0f8..70fd6b6c3606 100644 --- a/test/bundler/bundler_edgecase.test.ts +++ b/test/bundler/bundler_edgecase.test.ts @@ -3611,6 +3611,57 @@ describe("bundler", () => { api.expectFile("/out.js").toContain("var arguments = 1;"); }, }); + + // Without code splitting, each entry point gets its own output file, even when + // entry points import each other. Each file runs its modules in the order that + // its own entry point imports them, so it prints what the unbundled entry prints. + itBundled("edgecase/EntryPointsImportEachOther", { + files: { + "/a.ts": /* ts */ ` + import { b } from "./b.ts"; + export function a() { return "a"; } + console.log("a runs, b() is", b()); + `, + "/b.ts": /* ts */ ` + import { a } from "./a.ts"; + export function b() { return "b"; } + console.log("b runs, a() is", a()); + `, + }, + entryPoints: ["/a.ts", "/b.ts"], + outdir: "/out", + run: [ + { file: "/out/a.js", stdout: "b runs, a() is a\na runs, b() is b" }, + { file: "/out/b.js", stdout: "a runs, b() is b\nb runs, a() is a" }, + ], + }); + itBundled("edgecase/EntryPointImportsEntryPointModuleOrder", { + files: { + "/a.ts": `import "./c.ts"; import "./b.ts"; console.log("a");`, + "/b.ts": `import "./d.ts"; console.log("b");`, + "/c.ts": `console.log("c");`, + "/d.ts": `console.log("d");`, + }, + entryPoints: ["/a.ts", "/b.ts"], + outdir: "/out", + run: [ + { file: "/out/a.js", stdout: "c\nd\nb\na" }, + { file: "/out/b.js", stdout: "d\nb" }, + ], + }); + itBundled("edgecase/CSSEntryPointsImportEachOther", { + files: { + "/a.css": `@import "./b.css"; .a { color: red }`, + "/b.css": `@import "./a.css"; .b { color: blue }`, + }, + entryPoints: ["/a.css", "/b.css"], + outdir: "/out", + minifyWhitespace: true, + onAfterBundle(api) { + api.expectFile("/out/a.css").toEqualIgnoringWhitespace(".b{color:#00f}.a{color:red}"); + api.expectFile("/out/b.css").toEqualIgnoringWhitespace(".a{color:red}.b{color:#00f}"); + }, + }); }); for (const backend of ["api", "cli"] as const) { From afd9c2add8dcb6d64638c4874e937a9693934614 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 3 Sep 2026 04:10:44 +0000 Subject: [PATCH 2/5] test: an HTML script that is also an entry point runs in its place on the page --- test/bundler/bundler_html.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/test/bundler/bundler_html.test.ts b/test/bundler/bundler_html.test.ts index 34a1b75e15e8..cc36c530ad25 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -226,6 +226,29 @@ export const padZero = (num) => String(num).padStart(2, '0');`, }, }); + // A script that is also an entry point still runs in its place on the page. + itBundled("html/script-that-is-also-an-entry-point", { + outdir: "out/", + files: { + "/index.html": ` + + + + + + +`, + "/first.js": `console.log("first");`, + "/second.js": `console.log("second");`, + }, + entryPoints: ["/index.html", "/second.js"], + onAfterBundle(api) { + const jsMatch = api.readFile("out/index.html").match(/src="(.*\.js)"/); + expect(api.readFile("out/" + jsMatch![1])).toMatch(/"first"[\s\S]*"second"/); + api.expectFile("out/second.js").toContain('console.log("second")'); + }, + }); + // Test CSS imports itBundled("html/css-imports", { outdir: "out/", From b6e0e767e37810e42ac5fcd67656545c412edc8d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 3 Sep 2026 04:20:07 +0000 Subject: [PATCH 3/5] test: compare process.versions.bun without -debug on both sides In a debug build, --compile inlines process.versions.bun as "-debug". compile/HelloWorldWithProcessVersionsBun removed "-debug" only from the expected value, so it failed on every debug build. The API variant of the test already removes it from both values. --- test/bundler/bundler_compile.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index ac409393426c..ac147a1d9dbd 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -83,7 +83,7 @@ describe("bundler", () => { process.exitCode = 1; process.versions.bun = "bun!"; if (process.versions.bun === "bun!") throw new Error("fail"); - if (require("./${process.platform}-${process.arch}.js") === "${Bun.version.replaceAll("-debug", "")}") { + if (require("./${process.platform}-${process.arch}.js").replaceAll("-debug", "") === "${Bun.version.replaceAll("-debug", "")}") { process.exitCode = 0; } `, From 53c26202d3a290aedf0d0972fc821eae45492c40 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 3 Sep 2026 06:10:22 +0000 Subject: [PATCH 4/5] bundler: write module.exports only in the chunk of the file's entry point Without code splitting, the file of one entry point can print in the chunk of another entry point. In cjs output, that file assigned its own exports to module.exports and replaced the exports of the chunk. Its re-exports from other modules also went onto module.exports. Both writes now happen only when the file is the entry point of the chunk, as in esbuild. A file that is not an entry point also stops writing its re-exports to module.exports. importstar/ReExportStarEntryPointAndInnerFileExternal gets back the value that esbuild prints. The value changed when the test first ran with cjs output. Two entry points can name one file, for example when an onResolve plugin maps two names to it. LinkerGraph::load now keeps one entry point for the file, so the file gets one chunk and one output file. --- src/bundler/Chunk.rs | 7 +++ src/bundler/LinkerGraph.rs | 43 +++++++------------ .../linker_context/convertStmtsForChunk.rs | 6 +-- src/bundler/linker_context/doStep5.rs | 2 + .../generateCodeForFileInChunkJS.rs | 11 ++++- test/bundler/bundler_edgecase.test.ts | 31 +++++++++++++ test/bundler/bundler_plugin.test.ts | 28 ++++++++++++ test/bundler/esbuild/importstar.test.ts | 2 +- 8 files changed, 97 insertions(+), 33 deletions(-) diff --git a/src/bundler/Chunk.rs b/src/bundler/Chunk.rs index f7b732ff6099..3467412bd9ca 100644 --- a/src/bundler/Chunk.rs +++ b/src/bundler/Chunk.rs @@ -275,6 +275,13 @@ impl Chunk { self.entry_point.is_entry_point() } + /// Whether `source_index` is the entry point of this chunk. Without code + /// splitting, the files of other entry points can print in this chunk too. + #[inline] + pub(crate) fn is_entry_point_file(&self, source_index: u32) -> bool { + self.entry_point.is_entry_point() && self.entry_point.source_index() == source_index + } + /// Stable short name for this chunk in generated code: its final content hash, as `[hash]` prints it. pub(crate) fn id(&self) -> [u8; CHUNK_ID_LEN] { bun_core::fmt::truncated_hash32_bytes( diff --git a/src/bundler/LinkerGraph.rs b/src/bundler/LinkerGraph.rs index 6cf4ed4de45b..ba8cd4966d2f 100644 --- a/src/bundler/LinkerGraph.rs +++ b/src/bundler/LinkerGraph.rs @@ -687,39 +687,26 @@ impl<'a> LinkerGraph<'a> { + server_component_boundaries.list.len() + dynamic_import_entry_points.len(), )?; - // SAFETY: capacity reserved; columns initialized below. - unsafe { self.entry_points.set_len(entry_points.len()) }; - - // Note: `source_indices` / `path_strings` are disjoint columns of - // the same `MultiArrayList`. `split_mut()` hands out both at once; - // `self.entry_points` is not - // reallocated until after `path_strings`/`source_indices` are done - // with (the next `append_assume_capacity` is within the - // pre-reserved capacity, so no realloc). - let mut ep_slice = self.entry_points.slice(); - let ep_cols = ep_slice.split_mut(); - let source_indices: &mut [index::Int] = ep_cols.source_index; - let path_strings: &mut [RawSlice] = ep_cols.output_path; - - debug_assert_eq!(entry_points.len(), path_strings.len()); - debug_assert_eq!(entry_points.len(), source_indices.len()); - for ((i, path_string), source_index) in entry_points - .iter() - .zip(path_strings.iter_mut()) - .zip(source_indices.iter_mut()) - { + for i in entry_points { let source = &sources[i.get() as usize]; debug_assert!(source.index.0 == i.get()); - entry_point_kinds[source.index.0 as usize] = entry_point::Kind::UserSpecified; - // Check if this entry point has an original name (from virtual entry resolution) - if let Some(original_name) = entry_point_original_names.get(i.get()) { - *path_string = RawSlice::new(original_name); - } else { - *path_string = RawSlice::new(source.path.text); + // Two entry points can name one file, e.g. when an onResolve plugin + // maps two names to it. The file gets one entry point and one output. + if entry_point_kinds[source.index.0 as usize] != entry_point::Kind::None { + continue; } + entry_point_kinds[source.index.0 as usize] = entry_point::Kind::UserSpecified; - *source_index = source.index.0; + // Check if this entry point has an original name (from virtual entry resolution) + let output_path = match entry_point_original_names.get(i.get()) { + Some(original_name) => RawSlice::new(original_name), + None => RawSlice::new(source.path.text), + }; + self.entry_points.append_assume_capacity(EntryPoint { + source_index: source.index.0, + output_path, + }); } for &id in dynamic_import_entry_points { diff --git a/src/bundler/linker_context/convertStmtsForChunk.rs b/src/bundler/linker_context/convertStmtsForChunk.rs index be66b2a2f6f3..258b0dfbcfda 100644 --- a/src/bundler/linker_context/convertStmtsForChunk.rs +++ b/src/bundler/linker_context/convertStmtsForChunk.rs @@ -62,15 +62,15 @@ pub(crate) fn convert_stmts_for_chunk( let output_format = c.options.output_format; - // If this file is a CommonJS entry point, double-write re-exports to the - // external CommonJS "module.exports" object in addition to our internal ESM + // If this file is the CommonJS entry point of this chunk, double-write re-exports + // to the external CommonJS "module.exports" object in addition to our internal ESM // export namespace object. The difference between these two objects is that // our internal one must not have the "__esModule" marker while the external // one must have the "__esModule" marker. This is done because an ES module // importing itself should not see the "__esModule" marker but a CommonJS module // importing us should see the "__esModule" marker. let mut module_exports_for_export: Option = None; - if output_format == Format::Cjs && chunk.is_entry_point() { + if output_format == Format::Cjs && chunk.is_entry_point_file(source_index) { module_exports_for_export = Some(Expr::allocate( bump, E::Dot { diff --git a/src/bundler/linker_context/doStep5.rs b/src/bundler/linker_context/doStep5.rs index a276609e9808..daf39d760da0 100644 --- a/src/bundler/linker_context/doStep5.rs +++ b/src/bundler/linker_context/doStep5.rs @@ -758,6 +758,8 @@ impl LinkerContext<'_> { // instead of by mutating the exports object because other modules in the // bundle (including the entry point module) may do "import * as" to get // access to the exports object and should NOT see the "__esModule" flag. + // This stays the last statement of the part: `generate_code_for_file_in_chunk_js` + // drops it when another entry point's chunk prints this file. if force_include_exports_for_entry_point { let to_common_js_ref = self.runtime_function(b"__toCommonJS"); emit_export_stmt!(Stmt::assign( diff --git a/src/bundler/linker_context/generateCodeForFileInChunkJS.rs b/src/bundler/linker_context/generateCodeForFileInChunkJS.rs index 44f4c42708b2..f7ba8e07ca3c 100644 --- a/src/bundler/linker_context/generateCodeForFileInChunkJS.rs +++ b/src/bundler/linker_context/generateCodeForFileInChunkJS.rs @@ -286,8 +286,17 @@ pub fn generate_code_for_file_in_chunk_js<'r, 'src>( && parts_live.is_set(namespace_export_part_index as usize) { // SAFETY: see `parts` raw-pointer note above; index bounded by the range check just above. - let ns_part_stmts: &[Stmt] = + let mut ns_part_stmts: &[Stmt] = unsafe { (*parts)[namespace_export_part_index as usize].stmts }.slice(); + // Step 5 ends this part of a CommonJS entry point with + // `module.exports = __toCommonJS(exports)`. Only the chunk of that entry point runs it. + if output_format == OutputFormat::Cjs + && flags.force_include_exports_for_entry_point + && !chunk.is_entry_point_file(source_index as u32) + && let Some((_module_exports, rest)) = ns_part_stmts.split_last() + { + ns_part_stmts = rest; + } if let Err(err) = convert_stmts_for_chunk( c, source_index as u32, diff --git a/test/bundler/bundler_edgecase.test.ts b/test/bundler/bundler_edgecase.test.ts index 70fd6b6c3606..8f1875011b7f 100644 --- a/test/bundler/bundler_edgecase.test.ts +++ b/test/bundler/bundler_edgecase.test.ts @@ -3662,6 +3662,37 @@ describe("bundler", () => { api.expectFile("/out/b.css").toEqualIgnoringWhitespace(".a{color:red}.b{color:#00f}"); }, }); + // With --format=cjs, the module.exports of each output holds the exports of its + // own entry point, also when the file of another entry point prints in it. + itBundled("edgecase/EntryPointsImportEachOtherCommonJS", { + files: { + "/a.ts": `import { b } from "./b.ts"; export function a() { return b(); }`, + "/b.ts": `import { a } from "./a.ts"; export function b() { return "b"; } export const useA = () => a;`, + }, + runtimeFiles: { + "/check.js": `console.log(JSON.stringify([require("./out/a.js"), require("./out/b.js")].map(Object.keys)));`, + }, + entryPoints: ["/a.ts", "/b.ts"], + outdir: "/out", + format: "cjs", + run: { file: "/check.js", stdout: `[["a"],["b","useA"]]` }, + }); + itBundled("edgecase/EntryPointImportsEntryPointCommonJS", { + files: { + "/index.ts": `import { x } from "./lib.ts"; export const y = x + 1;`, + "/lib.ts": `export * from "ext"; export const x = 1;`, + }, + runtimeFiles: { + "/node_modules/ext/index.js": `module.exports = { fromExt: true };`, + "/check.js": `console.log(JSON.stringify([require("./out/index.js"), require("./out/lib.js")]));`, + }, + entryPoints: ["/index.ts", "/lib.ts"], + outdir: "/out", + external: ["ext"], + target: "node", + format: "cjs", + run: { file: "/check.js", stdout: `[{"y":2},{"x":1,"fromExt":true}]` }, + }); }); for (const backend of ["api", "cli"] as const) { diff --git a/test/bundler/bundler_plugin.test.ts b/test/bundler/bundler_plugin.test.ts index 302216980356..e9312694e2b2 100644 --- a/test/bundler/bundler_plugin.test.ts +++ b/test/bundler/bundler_plugin.test.ts @@ -1865,4 +1865,32 @@ describe("bundler", () => { }); expect(exitCode).toBe(0); }); + + // Two entry point names that onResolve maps to one file make one output file. + for (const splitting of [false, true]) { + test.concurrent(`plugin/two entry points that resolve to one file (splitting: ${splitting})`, async () => { + using dir = tempDir("plugin-two-entry-points-one-file", { + "entry.ts": `console.log("entry");`, + }); + const result = await Bun.build({ + entrypoints: ["first-name", "second-name"], + outdir: join(String(dir), "out"), + splitting, + throw: false, + plugins: [ + { + name: "alias", + setup(build) { + build.onResolve({ filter: /-name$/ }, () => ({ path: join(String(dir), "entry.ts") })); + }, + }, + ], + }); + expect({ + success: result.success, + logs: result.logs.map(log => log.message), + outputs: result.outputs.map(output => path.basename(output.path)), + }).toEqual({ success: true, logs: [], outputs: ["second-name.js"] }); + }); + } }); diff --git a/test/bundler/esbuild/importstar.test.ts b/test/bundler/esbuild/importstar.test.ts index b90a775240ef..79c29d6074c7 100644 --- a/test/bundler/esbuild/importstar.test.ts +++ b/test/bundler/esbuild/importstar.test.ts @@ -1434,7 +1434,7 @@ describe.concurrent("bundler", () => { }, run: { file: "/test.js", - stdout: '{"inner":{"b":456},"a":123,"b":456}', + stdout: '{"inner":{"b":456},"a":123}', }, }); itBundled("importstar/ReExportStarEntryPointAndInnerFile", { From 4701edf8d6bc7023a461710dd48f069ae7ab1b72 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 3 Sep 2026 07:20:14 +0000 Subject: [PATCH 5/5] bundler: call an entry point's ESM wrapper in cjs output only when it exists A file that something require()s gets an ESM wrapper. When all of its top-level statements hoist, the parser gives the file no wrapper symbol, and the printer prints the file with no wrapper. In cjs output, the tail of that entry point still called the missing wrapper. It printed `__INVALID__REF__();`, so loading the output threw a ReferenceError. The esm tail already checks that the symbol exists. --- .../linker_context/postProcessJSChunk.rs | 4 ++- test/bundler/bundler_edgecase.test.ts | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/bundler/linker_context/postProcessJSChunk.rs b/src/bundler/linker_context/postProcessJSChunk.rs index 2a7874fff764..2e7da0c1c7fb 100644 --- a/src/bundler/linker_context/postProcessJSChunk.rs +++ b/src/bundler/linker_context/postProcessJSChunk.rs @@ -1224,7 +1224,9 @@ pub(crate) fn generate_entry_point_tail_js<'a>( ), )); } - crate::WrapKind::Esm => { + // A file without a wrapper symbol prints unwrapped (`needs_wrapper_ref` + // in the parser), so there is no `init_foo` to call. + crate::WrapKind::Esm if ast.wrapper_ref.is_valid() => { // "init_foo();" stmts.push(Stmt::alloc( S::SExpr { diff --git a/test/bundler/bundler_edgecase.test.ts b/test/bundler/bundler_edgecase.test.ts index 8f1875011b7f..255d31f6ace0 100644 --- a/test/bundler/bundler_edgecase.test.ts +++ b/test/bundler/bundler_edgecase.test.ts @@ -3693,6 +3693,33 @@ describe("bundler", () => { format: "cjs", run: { file: "/check.js", stdout: `[{"y":2},{"x":1,"fromExt":true}]` }, }); + // A file that something require()s gets an ESM wrapper. When all of its + // top-level statements hoist, the wrapper is empty and is not printed, so the + // output of that entry point has no wrapper to call. + itBundled("edgecase/EntryPointRequiredByEntryPointCommonJS", { + files: { + "/a.ts": `const b = require("./b.ts"); export const fromA = b.x;`, + "/b.ts": `export const x = 1; export const y = 2;`, + }, + runtimeFiles: { + "/check.js": `console.log(JSON.stringify([require("./out/a.js"), require("./out/b.js")]));`, + }, + entryPoints: ["/a.ts", "/b.ts"], + outdir: "/out", + format: "cjs", + run: { file: "/check.js", stdout: `[{"fromA":1},{"x":1,"y":2}]` }, + }); + itBundled("edgecase/RequiredEntryPointWithoutWrapperCommonJS", { + files: { + "/entry.ts": `export function load() { return require("./c.ts"); } export const x = 1;`, + "/c.ts": `module.exports = require("./entry.ts");`, + }, + runtimeFiles: { + "/check.js": `const m = require("./out.js"); console.log(JSON.stringify(m), m.load() === m);`, + }, + format: "cjs", + run: { file: "/check.js", stdout: `{"x":1} true` }, + }); }); for (const backend of ["api", "cli"] as const) {