oven-sh / bun

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

Bun build has side effects when exporting a Class from a plugin library's package.json #13967

Open j4w8n opened 6 days ago

j4w8n commented 6 days ago

What version of Bun is running?

1.1.26 - is a dep for library and dev dep for test package

What platform is your computer?

WSL

What steps can reproduce the bug?

I've resolved this issue (see Additional Information) but wanted to create an issue for documentation, or in case this can be resolved with a PR. I'm not sure if this affects any library your package is using, or if it's just when using a Bun plugin from a library.

  1. Create a library that exports a minimal Bun plugin, a generic function, and a generic js/ts Class, from a file like ./lib/exports/index.js. Then link it globally with bun link.
  2. The library should have an exports statement in it's package.json similar to below (or whatever file you want to use).
    "exports": {
    ".": {
      "import": "./lib/exports/index.js"
    }
    }
  3. Create a test package and link the plugin library as a dev dependency.
  4. Create an index.ts file for your test package and import the generic function (this is a must) from the plugin library; but don't import the Class from the plugin library.
  5. Build index.ts, making sure you reference the plugin so it runs; and see the resulting index.js file has the Class' code even though it was never imported into index.ts

What is the expected behavior?

The Class code, and the waterfall imports from it's file, should only be included in code that imports the Class.

What do you see instead?

Code from the Class file is bundled into any files that have at least one import from the plugin library, but don't import the Class from the plugin library. The Class code does not show up in bundled files when their sources import nothing from the plugin library.

Additional information

I've resolved this issue by putting "sideEffects": false into my plugin library's package.json file. I'm just not sure if this is sometimes needed, is an indication that I've done something wrong in my plugin library, or is a bug with Bun.

It only does this with exported Classes. If you export functions from ./lib/exports/index.ts, their code is not included in bundled files unless those files explicitly import them.

j4w8n commented 2 days ago

I gleaned a small bit of knowledge from this: https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free