PluginBuilder

Bun

Symbol

PluginBuilder

interface PluginBuilder

The builder object passed to Bun.plugin

  • config: BuildConfig & { plugins: BunPlugin[] }

    The config object passed to Bun.build as is. Can be mutated.

  • module(specifier: string, callback: () => OnLoadResult | Promise<OnLoadResult>): this

    Create a lazy-loaded virtual module that can be imported or required from other modules

    @param specifier

    The module specifier to register the callback for

    @param callback

    The function to run when the module is imported or required

    Example

    @returns

    this for method chaining

    Bun.plugin({
      setup(builder) {
        builder.module("hello:world", () => {
          return { exports: { foo: "bar" }, loader: "object" };
        });
      },
    });
    
    // sometime later
    const { foo } = await import("hello:world");
    console.log(foo); // "bar"
    
    // or
    const { foo } = require("hello:world");
    console.log(foo); // "bar"
    
  • onBeforeParse(constraints: PluginConstraints, callback: { external: unknown; napiModule: unknown; symbol: string }): this
  • onLoad(constraints: PluginConstraints, callback: OnLoadCallback): this

    Register a callback to load imports with a specific import specifier

    @param constraints

    The constraints to apply the plugin to

    @param callback

    The callback to handle the import

    @returns

    this for method chaining

    Bun.plugin({
      setup(builder) {
        builder.onLoad({ filter: /^hello:world$/ }, (args) => {
          return { exports: { foo: "bar" }, loader: "object" };
        });
      },
    });
    
  • onResolve(constraints: PluginConstraints, callback: OnResolveCallback): this

    Register a callback to resolve imports matching a filter and/or namespace

    @param constraints

    The constraints to apply the plugin to

    @param callback

    The callback to handle the import

    @returns

    this for method chaining

    Bun.plugin({
      setup(builder) {
        builder.onResolve({ filter: /^wat$/ }, (args) => {
          return { path: "/tmp/woah.js" };
        });
      },
    });
    
  • onStart(callback: OnStartCallback): this

    Register a callback which will be invoked when bundling starts. When using hot module reloading, this is called at the start of each incremental rebuild.

    @returns

    this for method chaining

    Bun.plugin({
      setup(builder) {
        builder.onStart(() => {
          console.log("bundle just started!!")
        });
      },
    });