oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
74.5k stars 2.79k forks source link

Treeshaking with multiple entrypoints doesn't work properly #11476

Open mbkv opened 6 months ago

mbkv commented 6 months ago

What version of Bun is running?

1.1.10+5102a9443

What platform is your computer?

Linux 6.5.0-1016-oem x86_64 x86_64

What steps can reproduce the bug?

git clone https://github.com/mbkv/bun-treeshaking-bug.git
cd  bun-treeshaking-bug
bun install
bun run repro

or have the following files

// package.ts
export function entrypoint1Function() {
  console.log("Hello from entrypoint1");
}
export function entrypoint2Function() {
  console.log("Hello from entrypoint2");
}

// entrypoint1.ts
import { entrypoint1Function } from './package';
entrypoint1Function();

// entrypoint2.ts
import { entrypoint2Function } from './package';
entrypoint2Function();

and build with

bun build entrypoint1.ts entrypoint2.ts --outdir dist

It is now immediately obvious in the dist files that both entrypoint1Function and entrypoint2Function are included in both built files

dist/entrypoint1.js

// src/package1.ts
function entrypoint1Function() {
  console.log("Hello from entrypoint1");
}
function entrypoint2Function() {
  console.log("Hello from entrypoint2");
}

// src/entrypoint1.ts
entrypoint1Function();

dist/entrypoint2.js

// src/package1.ts
function entrypoint1Function() {
  console.log("Hello from entrypoint1");
}
function entrypoint2Function() {
  console.log("Hello from entrypoint2");
}

// src/entrypoint2.ts
entrypoint2Function();

building the entrypoints individually works as expected

What is the expected behavior?

No response

What do you see instead?

No response

Additional information

No response

Jarred-Sumner commented 6 months ago

I think you want --splitting

mbkv commented 6 months ago

No, and that's my fault for not being clear enough. I expected the built files but without the unused functions

dist/entrypoint1.js

// src/package1.ts
function entrypoint1Function() {
  console.log("Hello from entrypoint1");
}

// src/entrypoint1.ts
entrypoint1Function();

dist/entrypoint2.js

// src/package1.ts
function entrypoint2Function() {
  console.log("Hello from entrypoint2");
}

// src/entrypoint2.ts
entrypoint2Function();

This is the same output I get when I run bun build on the individual files like such, which makes me think this is a bug and not intentional

bun build  src/entrypoint1.ts --outdir dist
bun build  src/entrypoint2.ts --outdir dist

My use case is a little strange. I was playing the game Bitburner when I noticed. The game is a programming game where you use javascript to automate parts of the game. Each API has a resource cost, but the game doesn't do any static analysis if the APIs are actually used, so if each built file doesn't do treeshaking properly, each automation uses up a lot more resources than is necessary