Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What are the differences between onResolve and onLoad in Bun plugins
    differences between onResolve onLoad plugins


What are the differences between onResolve and onLoad in Bun plugins


In Bun plugins, `onResolve` and `onLoad` serve distinct purposes in the module resolution and loading process. Here are the key differences between them:

onResolve

- Purpose: The `onResolve` hook is used to intercept and modify the resolution of module paths. It allows you to define custom behavior when a module is being resolved, such as redirecting imports or modifying the path.

- Callback Arguments: The callback for `onResolve` receives an object containing properties like `path` (the path of the module being resolved) and `importer` (the path of the module that is importing it). This enables you to determine how to handle the resolution based on these values.

- Return Value: The return value can specify a new path or namespace for the resolved module, allowing for redirection or aliasing of imports.

- Use Case: This hook is useful for scenarios like implementing custom import maps, handling non-standard protocols, or providing alternative paths for modules.

onLoad

- Purpose: The `onLoad` hook is used to handle the loading of modules after they have been resolved. It allows you to define how to load the contents of a module once its path has been determined.

- Callback Arguments: The callback for `onLoad` receives an object with properties like `path`, which indicates the path of the file being loaded.

- Return Value: The return value must include either `contents` (the source code of the module) and `loader` (the type of loader used) or an `exports` object if the loader type is `"object"`.

- Use Case: This hook is ideal for transforming or processing file contents, such as transpiling TypeScript to JavaScript, loading YAML files, or applying any custom logic to the contents before they are executed.

Summary

In summary, use `onResolve` to control how modules are resolved (i.e., where Bun looks for them), and use `onLoad` to control how those resolved modules are loaded and processed. This separation allows for a flexible and powerful plugin system in Bun that can handle various scenarios in module management effectively [1][3][5].

Citations:
[1] https://nodejs.libhunt.com/bun-alternatives
[2] https://github.com/oven-sh/bun/issues/9863
[3] https://bun.sh/docs/bundler/vs-esbuild
[4] https://blog.stackademic.com/unveiling-buns-potential-with-typescript-1ca01e150595?gi=034abd9f12d6
[5] https://bun.sh/docs/runtime/plugins
[6] https://bun.sh/docs/bundler/plugins
[7] https://b-nova.com/en/home/content/bun-and-its-innovations/
[8] https://bun.sh/docs/runtime/bunfig