#How tf do you make a plugin that works without compiling?

1 messages · Page 1 of 1 (latest)

eternal quiver
#

I've spent like 3h on this now, tried to follow documentation. Spammed @zealous lantern, literally can't figure it out.

Does anyone have an example that works for both compile and not compiled? ./binary bun run .

Thanks

zealous lanternBOT
#

Thanks for tagging me @eternal quiver. I'll look through relevant sources and get back to you shortly.

#

Answer

Plugins work differently depending on whether you're running directly with bun run vs compiling with bun build --compile.

**For runtime (non-compiled) **, you register plugins using Bun.plugin() typically via a preload script:
(1)

import { plugin } from "bun";

plugin({
  name: "Custom loader",
  setup(build) {
    // implementation
  },
}) ;

For compiled executables, plugins must be passed into the plugins array when calling Bun.build() :
(2)

import type { BunPlugin } from "bun";

const envPlugin: BunPlugin = {
  name: "env-loader",
  setup(build) {
    build.onLoad({ filter: /\.env\.json$/ }, async args => {
      const env = await Bun.file(args.path) .json() ;
      return {
        contents: `export default ${JSON.stringify(env) };`,
        loader: "js",
      };
    }) ;
  },
};

await Bun.build({
  entrypoints: ["./cli.ts"],
  compile: {
    outfile: "./mycli",
  },
  plugins: [envPlugin],
}) ;

Key point: As of Bun v1.2.21, Bun.build supports compile: true which unblocks build-time plugins.
(3) , (4)

So to have something work in both scenarios, you'd need:

  1. A preload script with Bun.plugin() for bun run
  2. A build script that passes the same plugin logic to Bun.build({ plugins: [...], compile: true }) for compilation

The plugin definition itself can be shared, but the registration mechanism differs between runtime and build-time.

#

Feel free to tag @zealous lantern with additional questions. I also appreciate feedback, it helps me improve.

eternal quiver
#

ignore that, it doesnt help

#

to note, I've noticed a mismatch in behaviour for module resolution, it always works when compiled, but never when not compiled

zealous lanternBOT
zealous lanternBOT