Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
2 changes: 1 addition & 1 deletion docs/bundler/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1402,7 +1402,7 @@ This works for **pure barrel files** — files where every named export is a re-

The bundler always loads `export *` re-exports (it never defers them) to avoid circular resolution issues. It defers only named re-exports (`export { X } from './x'`) that no importer uses.

**Automatic mode:** Packages with `"sideEffects": false` in their `package.json` get barrel optimization automatically — no `optimizeImports` config needed. Use `optimizeImports` for packages that don't have this field.
**Automatic mode:** Packages with `"sideEffects": false` in their `package.json` get barrel optimization automatically — no `optimizeImports` config needed. Use `optimizeImports` for packages that don't have this field. `ignoreDCEAnnotations` (`--ignore-dce-annotations`) turns automatic mode off: the bundler then loads every re-export of such a barrel.

**Plugins:** Resolve and load plugins work with barrel optimization. Deferred submodules go through the plugin pipeline when they are eventually loaded.

Expand Down
2 changes: 1 addition & 1 deletion docs/snippets/cli/run.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ bun run <file or script>
</ParamField>

<ParamField path="--ignore-dce-annotations" type="boolean">
Ignore tree-shaking annotations such as <code>@__PURE__</code>
Ignore tree-shaking annotations such as <code>@__PURE__</code> and <code>"sideEffects"</code> in package.json
</ParamField>

### Networking &amp; Security
Expand Down
6 changes: 5 additions & 1 deletion packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3371,6 +3371,9 @@ declare module "bun" {
* Ignore dead code elimination/tree-shaking annotations such as @__PURE__ and package.json
* "sideEffects" fields. This should only be used as a temporary workaround for incorrect
* annotations in libraries.
*
* A barrel file of a `"sideEffects": false` package then loads all of its re-exports.
* Packages listed in `optimizeImports` stay optimized.
*/
ignoreDCEAnnotations?: boolean;

Expand Down Expand Up @@ -3492,7 +3495,8 @@ declare module "bun" {
* skipped entirely.
*
* This is also enabled automatically for any package with
* `"sideEffects": false` in its `package.json`.
* `"sideEffects": false` in its `package.json`, unless
* `ignoreDCEAnnotations` is set.
*
* @example
* ```ts
Expand Down
11 changes: 8 additions & 3 deletions src/bundler/barrel_imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ fn resolve_barrel_export(
/// import records as is_unused so they won't be resolved. Runs BEFORE resolution.
///
/// A file qualifies as a barrel if:
/// 1. It has `sideEffects: false` or is in `optimize_imports`, AND
/// 1. It has `sideEffects: false` (unless `--ignore-dce-annotations`) or is in
/// `optimize_imports`, AND
Comment thread
robobun marked this conversation as resolved.
Resolved
/// 2. All named exports are re-exports (no local definitions), AND
/// 3. It is not an export star target of another barrel.
///
Expand Down Expand Up @@ -115,11 +116,15 @@ fn apply_barrel_optimization_impl(
} else {
false
};
let is_side_effects_false =
result.side_effects == bun_ast::SideEffects::NoSideEffectsPackageJson;
let is_side_effects_false = result.side_effects
== bun_ast::SideEffects::NoSideEffectsPackageJson
&& !this.linker.options.ignore_dce_annotations;
if !is_explicit && !is_side_effects_false {
return Ok(());
}
if !this.is_barrel_optimization_enabled() {
return Ok(());
}
// An entry point's exports are the public interface of the build. No file
// imports an entry point, so nothing seeds `requested_exports` for it and a
// deferred record would never be un-deferred. The linked output would then
Expand Down
16 changes: 13 additions & 3 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ pub struct BundleV2<'a> {
/// If false we can skip TLA validation and propagation.
pub(crate) has_any_top_level_await_modules: bool,

/// The import graph is the result, and nothing is printed: set by
/// `scan_module_graph_from_cli`, and by `generate_from_cli` for a
/// `DependenciesScanner`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) scan_only: bool,

/// Barrel optimization: tracks which exports have been requested from each
/// module encountered during barrel BFS. Keys are source indices. Values
/// track requested export names for deduplication and cycle detection.
Expand Down Expand Up @@ -3288,6 +3293,7 @@ pub mod bv2_impl {
drain_defer_task: DeferredBatchTask::default(),
asynchronous: false,
has_any_top_level_await_modules: false,
scan_only: false,
requested_exports: Vec::new(),
});
if let Some(bo) = bake_options {
Expand Down Expand Up @@ -4428,6 +4434,7 @@ pub mod bv2_impl {
alloc,
)?;
this.unique_key = generate_unique_key();
this.scan_only = fetcher.is_some();

// Wrap so every exit path (incl. `?`) hits the cleanup below.
let result = (|| -> Result<BuildResult, Error> {
Expand Down Expand Up @@ -4567,6 +4574,7 @@ pub mod bv2_impl {
) -> Result<Box<BundleV2<'a>>, Error> {
let mut this = BundleV2::init(transpiler, None, alloc, event_loop, false, None, alloc)?;
this.unique_key = generate_unique_key();
this.scan_only = true;

if this.transpiler.log().has_errors() {
return Err(crate::Error::BuildFailed);
Expand Down Expand Up @@ -6452,9 +6460,11 @@ pub mod bv2_impl {

/// Returns true when barrel optimization is enabled. Barrel optimization
/// can apply to any package with sideEffects: false or listed in
/// optimize_imports, so it is always enabled during bundling.
fn is_barrel_optimization_enabled(&self) -> bool {
true
/// optimize_imports, so it is always enabled during bundling. A scan
/// needs every edge of the import graph, and a deferred record has no
/// target.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn is_barrel_optimization_enabled(&self) -> bool {
!self.scan_only
Comment thread
robobun marked this conversation as resolved.
Resolved
}

// TODO: remove ResolveQueue
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/cli/Arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ const TRANSPILER_PARAMS_: &[ParamType] = &[
"--jsx-side-effects Treat JSX elements as having side effects (disable pure annotations)"
),
parse_param!(
"--ignore-dce-annotations Ignore tree-shaking annotations such as @__PURE__"
"--ignore-dce-annotations Ignore tree-shaking annotations such as @__PURE__ and \"sideEffects\" in package.json"
),
];

Expand Down
111 changes: 111 additions & 0 deletions test/bundler/bundler_barrel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2271,4 +2271,115 @@ describe("bundler", () => {
expect(a).toContain("used value");
expect(a).toBe(b);
});

// --- ignoreDCEAnnotations turns automatic mode off ---
// "sideEffects": false is an annotation, and the flag says not to trust it.
// A barrel then defers nothing on the word of its package.json: the linker
// keeps every import with the flag, so each re-export has to load.

const annotatedBarrel = (reExport: string) => ({
"/entry.js": /* js */ `
import { a } from 'barrel-pkg';
console.log(a, globalThis.b, globalThis.other);
`,
"/node_modules/barrel-pkg/package.json": JSON.stringify({
name: "barrel-pkg",
main: "./index.js",
sideEffects: false,
}),
"/node_modules/barrel-pkg/index.js": /* js */ `
export { a } from './a.js';
export { b } from './b.js';
${reExport}
`,
"/node_modules/barrel-pkg/a.js": /* js */ `
export const a = "a";
`,
"/node_modules/barrel-pkg/b.js": /* js */ `
globalThis.b = "b ran";
export const b = 1;
`,
"/node_modules/other-pkg/package.json": JSON.stringify({
name: "other-pkg",
main: "./index.js",
sideEffects: false,
}),
"/node_modules/other-pkg/index.js": /* js */ `
globalThis.other = "other-pkg ran";
export const other = 1;
`,
});

for (const backend of ["cli", "api"] as const) {
itBundled(`barrel/IgnoreDCEAnnotationsLoadsEveryReExport/${backend}`, {
files: annotatedBarrel(`export { other } from 'other-pkg';`),
ignoreDCEAnnotations: true,
backend,
outdir: "/out",
run: { stdout: "a b ran other-pkg ran" },
});

// Without the flag nothing asks for this name, and nothing resolves it.
// With the flag it is an import like any other.
itBundled(`barrel/IgnoreDCEAnnotationsReportsUnresolvableReExport/${backend}`, {
files: annotatedBarrel(`export { gone } from 'not-installed-pkg';`),
ignoreDCEAnnotations: true,
backend,
outdir: "/out",
bundleErrors: {
"/node_modules/barrel-pkg/index.js": ['Could not resolve: "not-installed-pkg"'],
},
});
}

// The same barrel without the flag: b.js and other-pkg stay unloaded.
itBundled("barrel/WithoutIgnoreDCEAnnotationsSkipsUnusedReExports", {
files: annotatedBarrel(`export { other } from 'other-pkg';`),
outdir: "/out",
run: { stdout: "a undefined undefined" },
});

// Only the plugin can resolve "virtual-dep". With the flag the plugin is
// asked, and the module it names loads.
itBundled("barrel/IgnoreDCEAnnotationsAsksResolvePlugin", ({ root }) => {
const resolved: string[] = [];
return {
files: {
...annotatedBarrel(`export { virtual } from 'virtual-dep';`),
"/virtual-dep.js": /* js */ `
globalThis.other = "virtual-dep ran";
export const virtual = 1;
`,
},
ignoreDCEAnnotations: true,
outdir: "/out",
plugins(builder) {
resolved.length = 0;
builder.onResolve({ filter: /^virtual-dep$/ }, args => {
resolved.push(args.path);
return { path: join(root, "virtual-dep.js") };
});
},
run: { stdout: "a b ran virtual-dep ran" },
onAfterBundle() {
expect(resolved).toEqual(["virtual-dep"]);
},
};
});

// optimizeImports is the user's word, not an annotation of the package: a
// listed package stays optimized with the flag. b.js would fail the build.
itBundled("barrel/IgnoreDCEAnnotationsKeepsOptimizeImports", {
files: {
...annotatedBarrel(`export { other } from 'other-pkg';`),
"/node_modules/barrel-pkg/package.json": JSON.stringify({ name: "barrel-pkg", main: "./index.js" }),
"/node_modules/barrel-pkg/b.js": /* js */ `
export const b = <<<SYNTAX_ERROR>>>;
`,
},
optimizeImports: ["barrel-pkg"],
ignoreDCEAnnotations: true,
outdir: "/out",
run: { stdout: "a undefined undefined" },
});
});
15 changes: 15 additions & 0 deletions test/cli/install/bun-add.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,21 @@ it("bun add --analyze goes by the package.json with a name that is nearest to th
expect(urls).toEqual([`${root_url}/bar`]);
});

// The bundler skips a re-export of a "sideEffects": false barrel that nothing imports. The runtime
// loads every file the barrel names, so the scan has to read them all.
it("bun add --analyze scans a file behind an unused re-export of a barrel", async () => {
const lib = join(package_dir, "lib");
await mkdir(lib, { recursive: true });
await writeFile(join(lib, "index.ts"), `export { a } from "./a"; export { b } from "./b";`);
await writeFile(join(lib, "a.ts"), `export const a = 1;`);
await writeFile(join(lib, "b.ts"), `import "bar/sub"; export const b = 2;`);
expect(
await analyze("add", `import { a } from "./lib"; console.log(a);`, {
packageJson: { name: "foo", sideEffects: false },
}),
).toEqual({ added: ["bar"], errors: [], exitCode: 0 });
});

it("bun add --analyze should scan dependencies", async () => {
const urls: string[] = [];
setHandler(dummyRegistry(urls));
Expand Down
19 changes: 19 additions & 0 deletions test/cli/test/test-changed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,25 @@ describe.concurrent("bun test --changed", () => {
expect(exitCode).toBe(0);
});

// The test runtime loads every file that a barrel re-exports, so a change
// to one of them can change the test. The bundler would skip b.ts here: the
// package is "sideEffects": false and nothing asks for `b`.
test("change behind an unused re-export of a barrel selects the importing test", async () => {
using dir = tempDir("test-changed-barrel", {
"package.json": JSON.stringify({ name: "barrel", type: "module", sideEffects: false }),
"src/index.ts": `export { a } from "./a";\nexport { b } from "./b";\n`,
"src/a.ts": `export const a = 1;\n`,
"src/b.ts": `export const b = 2;\n`,
"barrel.test.ts": `import { test, expect } from "bun:test";\nimport { a } from "./src/index";\ntest("barrel", () => expect(a).toBe(1));\n`,
});
initRepo(String(dir));
appendFileSync(join(String(dir), "src", "b.ts"), "// touched\n");

const { stderr, exitCode } = await runTestChanged(String(dir));
expect(ranFiles(stderr, ["barrel.test.ts"])).toEqual(["barrel.test.ts"]);
expect(exitCode).toBe(0);
});

test("staged changes are picked up", async () => {
using dir = tempDir("test-changed-staged", fixture);
initRepo(String(dir));
Expand Down
Loading