Repository navigation
Conversation
…module `export * from "path"` in a module that is not an entry point becomes `import * as ns from "path"` and `__reExport(exports_x, ns)`. The printer prints `* as ns` only for a record with `CONTAINS_IMPORT_STAR`, and that flag was missing. So the output had a bare `import "path"`, and `__reExport` threw `ReferenceError: path is not defined`. This happened for `import * as ns`, `import()`, and `require()` of such a module, for every external, in every release back to at least 1.3.5. Set the flag where the linker decides the export star runs at run time. The lifted CommonJS path already does this.
A module that `import()` (without splitting) or `require()` loads is printed
as `var init_x = __esm(() => {...})`. For `export * from "./x"` the
`init_x()` call belongs to the `export *` statement. An import through that
statement binds to the declaring file directly, so in a package with
`"sideEffects": false` nothing kept the statement, the call was dropped, and
the importer read `undefined`.
Step 3 of scan_imports_and_exports now records, for each export that arrives
through `export *` from a lazily initialized ES module, the statement that
initializes it. The import tracker, the entry point exports and the namespace
object add that statement to their dependencies, as they do for a named
re-export. In an unwrapped file without side effects such a statement is now
removable, so only the statement that a name is read through runs its module.
With code splitting, a chunk that depends on such a statement in another chunk
imports that chunk.
|
Status How I reproduced it:
The real package case is in the description too: The tests: The first commit of this branch is #41220. Merge #41220 first. A rebase then drops that commit from this branch. |
|
Updated 1:23 PM PT - Oct 24th, 2026
✅ @robobun, your commit c6247cee32a1262b83f4390ce32ef3d85ec11db3 passed in 🧪 To try this PR locally: bunx bun-pr 46786That installs a local version of the PR into your bun-46786 --bun |
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Record export-star initialization dependencies src/bundler/LinkerGraph.rs, src/bundler/bundle_v2.rs, src/bundler/linker_context/scanImportsAndExports.rs, src/bundler/LinkerContext.rs, src/bundler/linker_context/README.md |
The export traversal records initialization dependencies by file and symbol in LinkerGraph. The import tracker records the exporter, and the documentation updates the wrapper propagation description and example. |
Propagate dependencies through linking and chunks src/bundler/LinkerContext.rs, src/bundler/linker_context/scanImportsAndExports.rs, src/bundler/linker_context/doStep5.rs, src/bundler/linker_context/computeCrossChunkDependencies.rs, src/bundler/linker_context/README.md |
Import and namespace linking add recorded export-star statements as dependencies. The linker can remove unused plain export-star parts under the stated conditions. Cross-chunk calculation adds dependencies on chunks containing required export-star statements. |
Validate lazy and external star exports test/bundler/bundler_barrel.test.ts, test/bundler/esbuild/importstar.test.ts |
Tests cover lazy export-star reads and chains, code splitting, initialization order, side effects, exceptions, and external star exports. |
Possibly related issues
oven-sh/bun#46532— The changes track dependencies for bindings reached throughexport *, which relates to the issue’s export-preservation objective. The provided context does not establish that this fixes the Vitest case.
Suggested reviewers: jarred-sumner, alii
Priority:
Merge Risk: 
Minimal · up to c6247
-
No actionable issue was established that would prevent merging after normal checks.
Pre-merge checks: 
4
-
Full details: Description check
-
Explanation
The description thoroughly explains the problem, fix, behavior changes, limitations, performance impact, and verification results. It does not use the exact template headings, but it provides the required content and is substantially complete.
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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 @coderabbitai help to get the list of available commands.
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Beyond the inline findings, I also checked the new ImportTrackerIterator.exporter field across every constructor site in LinkerContext.rs — the non-Found paths all go through ..Default::default(), so exporter stays Index::INVALID and export_star_statement simply misses the map rather than reading a stale index. The amended LinkerGraph SAFETY comment holds: export_star_statements is assigned once at the end of the serial step 3 loop and only read afterwards. The --splitting chunk-cycle concern in computeCrossChunkDependencies.rs was examined and ruled out.
Extended reasoning...
Two confirmed findings are posted inline; this note records the adjacent checks that came up clean so a human reviewer need not repeat them.
| if can_drop_export_star | ||
| && kind == ImportKind::Stmt | ||
| && other_flags.wrap == WrapKind::Esm | ||
| && wrapper_ref.is_valid() | ||
| && !other_export_kind.is_dynamic() | ||
| { | ||
| let part = &mut col!(parts_list)[id].as_mut_slice()[part_index]; | ||
| if is_export_star_part(part) { | ||
| part.can_be_removed_if_unused = true; |
There was a problem hiding this comment.
🟡 (optional) Apps bundling a "sideEffects": false barrel whose export * target is lazily wrapped lose the target's top-level effects at load unless a name is read, unlike base, esbuild and node. scanImportsAndExports.rs:1262-1270 marks the part removable whenever the barrel is pure, without checking the target's own side-effect status at that point. The author sizes it at 32 of 922 graphs; packages that mis-declare sideEffects: false (common) and rely on export * running a registering module break silently. Fix: keep the part when the target file is not itself declared side-effect free, or when it has no named exports, matching base behaviour for those targets.
Why this was flagged
Trigger: pkg/package.json has "sideEffects": false, pkg/index.js is export * from './register.js' where register.js has top-level effects and is require()d or import()ed elsewhere (so wrap == Esm), and the app imports the barrel for some other name. The parts loop at scanImportsAndExports.rs:1262-1270 sets can_be_removed_if_unused = true on the export * part; the tree shaker at LinkerContext.rs:3164-3196 only re-keeps it when file_has_no_side_effects(other) is false, so if the target is in the same pure package (the normal case) nothing keeps the part and no init_register() is printed. Base, esbuild and node all run the target at barrel load. The user observes missing registrations/polyfills with exit code 0 and no warning. The dismissal accepted the PR text's rule; the PR itself admits main/esbuild/node differ and offers to keep main's output. Remedy: restrict the drop to targets that export at least one name and are themselves declared side-effect free.
Verification: nit — acknowledged in diff: the PR description lists it under "Downsides". scanImportsAndExports.rs:1262-1271 sets part.can_be_removed_if_unused = true on the export * part when the target is WrapKind::Esm; the tree shaker at LinkerContext.rs:3180-3181 skips a declared-pure target, so the part is dropped and the target's top-level code does not run at barrel load, diverging from base.
There was a problem hiding this comment.
This is the behaviour change that the description lists under Downsides and leaves to a maintainer. Facts for the two cases you name:
- A target that is not declared free of side effects keeps the statement already.
mark_file_live_stepmakes the part non-removable if the record's target has side effects. Checked on main and on this branch: a"sideEffects": falsebarrel that is in the bundle for an own export, withexport * from "dep/register.js"(dephas nosideEffectsfield, and animport()also loads the file), printsown registeron both. I add a test for it with the next push. - A target with no named export in the same side-effect-free package: I compared the three ways to write it, with the barrel in the bundle for an own export and
register.jsalso loaded by animport().
| statement in the barrel | node | main | this branch |
|---|---|---|---|
import "./register.js"; |
runs at load | does not run at load | does not run at load |
export {} from "./register.js"; |
runs at load | does not run at load | does not run at load |
export * from "./register.js"; |
runs at load | runs at load | does not run at load |
On main export * is the only form that runs a lazily loaded module of a side-effect-free package at load. This branch makes the three forms alike. If main's output is wanted for a barrel that is in the bundle for another reason, the section "The behaviour that changes on purpose" in the description says what it takes.
| if let Some(statement) = init_statement { | ||
| self.statements | ||
| .insert((target_id as u32, name.ref_), statement); |
There was a problem hiding this comment.
🟡 (optional) Readers of a name from a plain module pay for initializing a different lazily wrapped module and its whole import tree at load. scanImportsAndExports.rs:1785-1787 records the first path's statement only, so for export * from './lazy'; export * from './plain' where lazy re-exports plain, every plain name maps to the ./lazy statement and the droppable ./plain statement is removed. The bundle runs init_lazy() (all of lazy's body and dependencies) where init_plain() alone would do. Fix: prefer the shortest or direct export * statement when several paths reach the same declaring file, e.g. overwrite the entry when a later path's statement targets the declaring file itself.
Why this was flagged
Trigger: a sideEffects: false barrel with export * from './lazy' before export * from './plain', lazy also export * from './plain', something lazily require()s lazy, and a reader imports a name of plain through the barrel. add_exports walks lazy first (export_star_records order), sets lazy_file_entry at scanImportsAndExports.rs:1826, and inserts (barrel, plain.x) -> stmt_lazy at :1785-1787; the later direct path hits found_existing at :1775 and never updates the map. Step 4 at :1270 then marks the direct export * from './plain' part removable, so the output calls init_lazy() and not init_plain() directly. The reader's startup now executes lazy's full body (and every module it imports) even though only plain is needed; if lazy's body is heavy or throws under some runtime condition the reader breaks where the base, which initialized nothing and read undefined, at least did not execute lazy.
Verification: nit — a missed optimization relative to the PR's stated "one read name runs one module" goal, not a regression: the base branch and node both run lazy at load for this shape. Inside lazy, the ./plain record hits the Some((_, statement)) arm at src/bundler/linker_context/scanImportsAndExports.rs:1735-1741, so plain's names are inserted at 1785-1788 as (barrel, plain.x) -> stmt_lazy.
There was a problem hiding this comment.
Correct. For that shape the recorded statement is the one of ./lazy, and the bundle calls init_lazy(): the reader prints 7 plain lazy where 7 plain is enough. node and main run lazy at load there too, so it is a missed saving and no wrong value.
I tried the overwrite. With "a later direct statement replaces the recorded one", names that already have a direct statement move to a later one in another barrel file. In 2 of 1,579 random --splitting graphs a reader module then ran in a different order, because the statement was in another chunk. The version that is safe replaces only a statement that was taken over from a lazily loaded file above, and it has to look up the target of the recorded statement first.
I left the rule at "the first path wins", which is also the rule for the export itself (!gop.found_existing). The narrower overwrite can be a follow-up.
|
A correction for two lines of the description, under what this PR leaves as it is. They say that #41601 rewrites the
|
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-24. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Problem
bun buildexits 0, and a static import readsundefined:import { format } from "date-fns"beside a lazily loaded@mui/x-date-pickers/AdapterDateFnspage throwsTypeError: Cannot read properties of undefined (reading 'locale').export *binds to the declaring file directly (add_exports,scanImportsAndExports.rs:1679). Only theexport *statement callsinit_x(), and a"sideEffects": falsebarrel drops it.Fix
export *statement that initializes each export. A binding depends on it, like onexport { x } from.init_x(), not 62).--splitting, a chunk imports the chunk of a statement it depends on.test/bundler/bundler_barrel.test.ts(51 tests, 44 fail on main) andtest/bundler/. Self-reviewed: 30 concerns, 27 addressed.Background
require()and non-splittingimport()targets print asvar init_x = __esm(() => {...}). Static importers callinit_x()first."sideEffects": falselets tree shaking drop a file's unused statements.Downsides
export *runs at load, with the barrel's other effects. If it throws, so does the bundle, as in node.export *target (32 of 922 graphs), asexport { x } fromon main..text+7,168 B. With--splitting, files in the statement's chunk can run before the reader's chunk (7 of 1,579 graphs).Notes
No GitHub issue reports this. A design review of #45529 found it: that PR cannot merge before this one.
#41220 first. The first commit of this branch is #41220, unchanged. A barrel that a name is read through is kept, and a kept barrel prints each external
export *it has. Without #41220 that statement throwsReferenceError: node_path is not defined(barrel/ExportStarOfLazyModuleLoadsExternalExportStarOfBarrel). After #41220 merges, a rebase drops the commit from this branch. The second design that was weighed and rejected is a second tree-shaking pass that wraps the dropped barrel.Repro
node entry.mjs,bun entry.mjs200 500 500200 undefined undefinedundefined undefined undefined200 500 500esbuild has the same bug for this input, so this branch differs from esbuild on purpose. node is the reference.
Main prints no
init_lib()before the entry.movableis right on main only because the linker prints a side-effect-free initializer above the__esmwrapper. This branch prints// pkg/barrel.mjsandinit_lib();before the entry.The real package case:
entry.mjsisimport { format } from "date-fns"; console.log("static:", format(new Date(2020, 0, 2), "yyyy-MM-dd")); const page = await import("./picker-page.mjs"); page.show();andpicker-page.mjsimportsAdapterDateFnsfrom@mui/x-date-pickers/AdapterDateFns(date-fns 4.1.0, @mui/x-date-pickers 8). node printsstatic: 2020-01-02andlazy: 2021-06-06. The bundle from main throws at startup, and so does the bundle from esbuild 0.28.2.What makes a module lazily loaded
Any
require()of the module, and anyimport()of it without--splitting, in any file of the build. The edge can be in code that tree shaking drops, or in another entry point. A lazily loaded module also makes each module that it imports a lazily loaded one. So the bundle can have noimport()at all and still readundefinedon main (barrel/ExportStarOfLazyModuleLazyEdgeIsDropped).Which shapes were wrong (each reads
undefinedon main and is right on this branch)export *statements, and through a barrel that is itself the lazily loaded module.import * as nswithns.xreads,export * as nsin another file,export default ns.export * fromthe barrel, read by a consumer of the bundle.import(), asrequire(), as a lazily loaded module that imports the file, in a function that is never called, in dropped code, in another entry point.--format=esm,cjsandiife,--target=bun,nodeandbrowser, the CLI andBun.build,--minify,--bytecode,--compile.--splittingwith arequire()lazy edge: a reader in an entry chunk, and a reader in a chunk that two entry points share.How it works
add_exportswalks theexport *graph of each file. A wrapped file wraps every file it imports, so a path goes from unwrapped files into wrapped files once. The statement at that step printsinit_x(). For each export that arrives through it,add_exportsstores(file, export symbol) -> (file of the statement, part of the statement)inLinkerGraph::export_star_statements.match_import_with_export_inner, also used forns.x), the entry point export loop in step 6, andcreate_exports_for_filein step 5. Each adds the stored statement.export *as not removable. Without a change one used name would keep everyexport *of the barrel: on date-fns 62init_x()calls and 112 of 117 module bodies at startup. So step 6 marks anexport *part removable if all of these hold: the file is not wrapped, it is declared free of side effects, the target is a wrapped ES module with a wrapper, and the target has no dynamic exports.--splitting, chunk imports come from symbol uses. A part that depends on the statement uses no symbol of the statement's chunk.compute_cross_chunk_dependenciesnow adds that import. It scans part dependencies only if step 3 recorded a statement.convert_stmts_for_chunkand the printer are not changed.The behaviour that changes on purpose
In a
"sideEffects": falsebarrel that is in the bundle for another reason (one of its own exports is used), main, esbuild and node initialize a lazily loadedexport *target at load, also if nothing reads a name of it. On this branch such a module stays lazy, as it does forexport { x } fromon main (barrel/ExportStarOfLazyModuleStaysLazyBesideOwnExportOfBarrel).The first version of this branch kept main's output with a dependency from each other statement of the barrel. The self-review showed that one banner comment, one directive or one unread
export { x } fromin the barrel then ran every lazily loaded module of it (date-fns with a banner line: 62 calls). Main's output can be kept by cause in the tree shaker, at the cost of more code there. Say so if it is wanted.Two more consequences of the same rule:
export * from "./app.js"in a"sideEffects": falsepackage, withapp.jslazily loaded through an import cycle, raninit_app()on main. It now prints an empty chunk. Without the cycle main prints an empty chunk too.treeShaking: falsea file is one part, so one used name keeps the whole barrel (barrel/ExportStarOfLazyModuleTreeShakingOff).Measurements (x64 Linux, release builds of main 5c6d4e2 and of this branch, bundles run under node 26.3.0)
--splittingand compared with node on the source. 35 go from wrong to right (5 of them by bundler: name the namespace of an external export * in a non-entry module #41220). 44 are right on both builds. 3 go from right to a later evaluation of an unread module (the behaviour above). 34 differ from node on both builds, and 28 of them print the same on both.--splitting: 6,000 barrel graphs in a"sideEffects": falsepackage (named, namespace and re-exported reads,import()andrequire()lazy edges, externalexport *). The generator has no observable side effect, no import between leaf modules and no import cycle, and the comparison is on printed values. 4,625 are right on both builds, 1,375 go from wrong to right, 0 go from right to wrong, 0 stay wrong.--splitting --target=node: 1,579 graphs with readers shared byimport()pages and with observable evaluation order. A wrong value or a throw: 436 graphs on main (145 of them throw for bundler: name the namespace of an external export * in a non-entry module #41220), 0 on this branch. Order of reader modules only: 7 graphs go from right to a different order, 14 go from a different order to right, 204 differ on both builds, and 82 of the 436 have right values in a different order. The order difference is the one that plain shared modules have on main: a chunk runs after each chunk that it imports.export *and no lazy module is byte-identical.init_x()call, for a name that was right because its value was side-effect free or another import initialized the module). 32 lose 11 to 27 B (the unread module is no longer initialized at load). 9 gain up to 1,563 B (the kept barrel has an externalexport *).init_x()call at the barrel and 31 wrapper bodies run before the entry body.--splitting: the static startup closure goes from 50,458 to 50,521 B (--target=node) and from 51,801 to 51,864 B (browser). The lazy chunk keeps its 86 modules.export *enters a lazily loaded module, on the 2,001-module bundle (gdb breakpoint counts): 2,000 calls ofinit_statement_of_recordthat return at the first test, 10,000 tests of one local per flattened export, 14,033 calls ofexport_star_statementthat return onis_empty(). With--splitting, one moreis_empty()test per link. No allocation: the map allocates on its first insert. Whole-processinstructions:u, 25 interleaved runs: main 735.08 M, this branch 735.26 M (median, +0.18 M), with a spread of 4.4 M and 4.5 M. The delta is below the noise floor. valgrind and perf are not in the build container.export *statements.ImportTrackerIteratorstays 48 bytes (const assert).LinkerGraphgrows by one empty map (56 bytes)..text+7,168 B (size -A), with bundler: name the namespace of an external export * in a non-entry module #41220.scan_imports_and_exports56,421 to 59,020 B,match_import_with_export_inner7,463 to 7,869 B,compute_cross_chunk_dependencies15,324 to 17,487 B (nm -S).Not fixed here
export *: the statement printsinit_x()with noawait, also in a barrel that is kept. bundler: keep source order in a wrapper prefix that has no async dependency #41601 rewrites that code.init_y()above theexport *call, whatever the source order. In an import cycle this can change a value that was right while main dropped the barrel. bundler: keep source order in a wrapper prefix that has no async dependency #41601 orders these calls.export *barrel:ReferenceError: exports_barrel is not defined. Bun build does not import values re-exported from another package whensideEffectsisfalse#18008 tracks it.--splitting,export { x } fromof a lazily loaded module has no chunk import either: a reader in a shared chunk readsundefinedon main and on this branch.--splitting, a barrel that imports its reader back (an import cycle) can print theinit_x()call after the reader in a shared chunk, on main and on this branch.export *barrel, with no lazily loaded module. esbuild prints the same.export *target at load.Self-review
30 concerns. 27 addressed: the chunk import (a layout that is right on main read
undefinedunder--splittingon the first version), the removal of the keep-main dependency, the wording of this description, the README example, and 25 more tests. Not done here:sideEffectsisfalse#18008 (one condition in the branch below the one this PR edits). It is a separate change.todotests that the bundler: name the namespace of an external export * in a non-entry module #41220 commit makes pass (edgecase/ExternalES6ConvertedToCommonJSSimplified,default/ExternalES6ConvertedToCommonJS). They belong to bundler: name the namespace of an external export * in a non-entry module #41220.Tests
test/bundler/bundler_barrel.test.ts: 44 of the 51 tests fail on main. 7 pass on both builds and pin what must not change:UnreadStaysLazyOwnExportAndStarNameexport *in one importNamespaceValueimport * as nsused as a valueRequireOfBarrelrequire()of the barrel wraps the barrel, which callsinit_x()itselfEntryPointIsBarrelBarrelWithSideEffectsDeclarationOnlytest/bundler/esbuild/importstar.test.tshas the two tests of #41220.Suites: all of
test/bundler/with the release build of this branch, 7,673 pass.bundler_bytecode_portable.test.tsfails itslibraries.jspin in this container on main too, with the same received hashes on both builds. With the debug build:bundler_barrel(121 pass),esbuild/importstar(101 pass).