Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I override existing modules using Bun plugins


How do I override existing modules using Bun plugins


To override existing modules using Bun plugins, you can utilize the `build.module` method within the plugin's setup function. This allows you to define custom behavior for specific module imports. Here's how to do it:

Steps to Override Existing Modules

1. Import the Plugin Function: Start by importing the `plugin` function from Bun.

javascript
   import { plugin } from "bun";
   

2. Define Your Plugin: Create a plugin that overrides an existing module. Use the `build.module` method to specify the module you want to override and provide a callback that returns the desired exports.

javascript
   const myPlugin = plugin({
     name: "my-override-plugin",
     setup(build) {
       // Override an existing module
       build.module("existing-module-name", () => {
         return {
           exports: {
             foo: "bar", // Define the exports for the overridden module
           },
           loader: "object", // Specify the loader type
         };
       });
     },
   });
   

3. Register the Plugin: When building your application, include the plugin in the `plugins` array.

javascript
   Bun.build({
     entrypoints: ["./app.ts"],
     outdir: "./dist",
     plugins: [myPlugin],
   });
   

4. Usage: Once registered, any import of `"existing-module-name"` will now return your overridden exports.

Example

Here's a complete example that demonstrates overriding a module:

javascript
import { plugin } from "bun";

const myPlugin = plugin({
  name: "my-override-plugin",
  setup(build) {
    build.module("my-object-virtual-module", () => {
      return {
        exports: {
          foo: "bar", // New export for the overridden module
        },
        loader: "object",
      };
    });
  },
});

// Registering the plugin when building
Bun.build({
  entrypoints: ["./app.ts"],
  outdir: "./dist",
  plugins: [myPlugin],
});

// In your application code, you can now use:
import { foo } from "my-object-virtual-module"; // This will be "bar"

Notes

- The `build.module` method allows you to specify any string as a module name, except for built-in modules.
- This approach is particularly useful for creating virtual modules or modifying existing ones without altering their original implementations directly[1][4].

Citations:
[1] https://bun.sh/docs/runtime/plugins
[2] https://bun.sh/docs/install/overrides
[3] https://github.com/oven-sh/bun/issues/1134
[4] https://bun.sh/docs/bundler/plugins
[5] https://github.com/oven-sh/bun/issues/7965
[6] https://bun.sh/blog/bun-bundler
[7] https://bun.sh/docs/runtime/bunfig
[8] https://dev.to/thejaredwilcurt/bun-hype-how-we-learned-nothing-from-yarn-2n3j