oven-sh / bun

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

Plugin's setup function: `build.config` is undefined when using `Bun.plugin` #13695

Closed j4w8n closed 2 months ago

j4w8n commented 2 months ago

What version of Bun is running?

1.1.26+0a37423ba

What platform is your computer?

Linux 5.15.153.1-microsoft-standard-WSL2 x86_64 x86_64

What steps can reproduce the bug?

I'm building a third-party plugin and testing it in another package, using bun link. I build the project using bun run build, with a package.json script of "build": "bun run ./bun.build.ts".

/* bun.build.ts */
import { thing } from "some-package"

const build_result = await Bun.build({
  entrypoints: ['./index.ts'],
  outdir: 'out',
  plugins: [thing()],
})

console.log('result', build_result)

The relevant plugin code is:

const thing_plugin = {
  name: 'thing-bun-plugin',
  async setup (build) {
    console.log('build', build.config.outdir)
    await stuff()
    console.log('end setup')
  }
}

What is the expected behavior?

The value of build.config.outdir should be logged.

What do you see instead?

19 |     console.log('build', build.config.outdir)
                                    ^
TypeError: undefined is not an object (evaluating 'build.config.outdir')

Additional information

If I instead make config optional, with console.log('build', build.config?.outdir), everything works fine. But since the config is required in the type, I'm not expecting to have to do this to get it to work.

j4w8n commented 2 months ago

Think I figured out this issue. I believe it's because I'm using a third-party plugin for use in "dev" mode, to do one thing, and also in "build" mode to do another.

So, for runtime (dev) I have the plugin setup in a file called bun.plugin.ts; and this is referenced for preload in bunfig.toml. But, since I also need that plugin at buildtime, I have a typescript file called bun.build.ts that uses Bun.build() because this is currently the only way to use plugins at buildtime. Then, I have package.json script that executes the typescript file, to do the build.

This setup causes the plugin to run twice - first because the bunfig.toml preload runs it, since I'm executing a typescript file to trigger the build; then a second time when included with the Bun.build config. The TypeError is triggered on the preload run, since config doesn't actually exist in this case.