You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Plugins can read and write to the [build config](https://bun.sh/docs/bundler#api) with `build.config`.
308
308
@@ -327,7 +327,43 @@ Bun.build({
327
327
});
328
328
```
329
329
330
-
## Reference
330
+
{% callout %}
331
+
332
+
**NOTE**: Plugin lifcycle callbacks (`onStart()`, `onResolve()`, etc.) do not have the ability to modify the `build.config` object in the `setup()` function. If you want to mutate `build.config`, you must do so directly in the `setup()` function:
333
+
334
+
```ts
335
+
Bun.build({
336
+
entrypoints: ["./app.ts"],
337
+
outdir: "./dist",
338
+
sourcemap: "external",
339
+
plugins: [
340
+
{
341
+
name: "demo",
342
+
setup(build) {
343
+
// ✅ good! modifying it directly in the setup() function
344
+
build.config.minify=true;
345
+
346
+
build.onStart(() => {
347
+
// 🚫 uh-oh! this won't work!
348
+
build.config.minify=false;
349
+
});
350
+
},
351
+
},
352
+
],
353
+
});
354
+
```
355
+
356
+
{% /callout %}
357
+
358
+
## Lifecycle callbacks
359
+
360
+
Plugins can register callbacks to be run at various points in the lifecycle of a bundle:
361
+
362
+
-[`onStart()`](#onstart): Run once the bundler has started a bundle
363
+
-[`onResolve()`](#onresolve): Run before a module is resolved
364
+
-[`onLoad()`](#onload): Run before a module is loaded.
365
+
366
+
A rough overview of the types (please refer to Bun's `bun.d.ts` for the full type definitions):
`onLoad` and `onResolve` accept an optional `namespace` string. What is a namespaace?
402
+
403
+
Every module has a namespace. Namespaces are used to prefix the import in transpiled code; for instance, a loader with a `filter: /\.yaml$/` and `namespace: "yaml:"` will transform an import from `./myfile.yaml` into `yaml:./myfile.yaml`.
404
+
405
+
The default namespace is `"file"` and it is not necessary to specify it, for instance: `import myModule frmo "./my-module.ts"` is the same as `import myModule from "file:./my-module.ts"`.
406
+
407
+
Other common namespaces are:
408
+
409
+
-`"bun"`: for Bun-specific modules (e.g. `"bun:test"`, `"bun:sqlite"`)
410
+
-`"node"`: for Node.js modules (e.g. `"node:fs"`, `"node:path"`)
411
+
412
+
### `onStart`
413
+
414
+
```ts
415
+
onStart(callback: () =>void): Promise<void>|void;
416
+
```
417
+
418
+
Registers a callback to be run when the bundler starts a new bundle.
419
+
420
+
```ts
421
+
import { plugin } from"bun";
422
+
423
+
plugin({
424
+
name: "onStart example",
425
+
426
+
setup(build) {
427
+
build.onStart(() => {
428
+
console.log("Bundle started!");
429
+
});
430
+
},
431
+
});
432
+
```
433
+
434
+
The callback can return a `Promise`. After the bundle process has initialized, the bundler waits until all `onStart()` callbacks have completed before continuing.
435
+
436
+
For example:
437
+
438
+
```ts
439
+
const result =awaitBun.build({
440
+
entrypoints: ["./app.ts"],
441
+
outdir: "./dist",
442
+
sourcemap: "external",
443
+
plugins: [
444
+
{
445
+
name: "Sleep for 10 seconds",
446
+
setup(build) {
447
+
build.onStart(async () => {
448
+
awaitBunlog.sleep(10_000);
449
+
});
450
+
},
451
+
},
452
+
{
453
+
name: "Log bundle time to a file",
454
+
setup(build) {
455
+
build.onStart(async () => {
456
+
const now =Date.now();
457
+
awaitBun.$`echo ${now} > bundle-time.txt`;
458
+
});
459
+
},
460
+
},
461
+
],
462
+
});
463
+
```
464
+
465
+
In the above example, Bun will wait until the first `onStart()` (sleeping for 10 seconds) has completed, _as well as_ the second `onStart()` (writing the bundle time to a file).
466
+
467
+
Note that `onStart()` callbacks (like every other lifecycle callback) do not have the ability to modify the `build.config` object. If you want to mutate `build.config`, you must do so directly in the `setup()` function.
To bundle your project, Bun walks down the dependency tree of all modules in your project. For each imported module, Bun actually has to find and read that module. The "finding" part is known as "resolving" a module.
482
+
483
+
The `onResolve()` plugin lifecycle callback allows you to configure how a module is resolved.
484
+
485
+
The first argument to `onResolve()` is an object with a `filter` and [`namespace`](#what-is-a-namespace) property. The filter is a regular expression which is run on the import string. Effectively, these allow you to filter which modules your custom resolution logic will apply to.
486
+
487
+
The second argument to `onResolve()` is a callback which is run for each module import Bun finds that matches the `filter` and `namespace` defined in the first argument.
488
+
489
+
The callback receives as input the _path_ to the matching module. The callback can return a _new path_ for the module. Bun will read the contents of the _new path_ and parse it as a module.
490
+
491
+
For example, redirecting all imports to `images/` to `./public/images/`:
After Bun's bundler has resolved a module, it needs to read the contents of the module and parse it.
524
+
525
+
The `onLoad()` plugin lifecycle callback allows you to modify the _contents_ of a module before it is read and parsed by Bun.
526
+
527
+
Like `onResolve()`, the first argument to `onLoad()` allows you to filter which modules this invocation of `onLoad()` will apply to.
528
+
529
+
The second argument to `onLoad()` is a callback which is run for each matching module _before_ Bun loads the contents of the module into memory.
530
+
531
+
This callback receives as input the _path_ to the matching module, the _importer_ of the module (the module that imported the module), the _namespace_ of the module, and the _kind_ of the module.
532
+
533
+
The callback can return a new `contents` string for the module as well as a new `loader`.
This plugin will transform all imports of the form `import env from "env"` into a JavaScript module that exports the current environment variables.
554
+
555
+
#### `.defer()`
556
+
557
+
One of the arguments passed to the `onLoad` callback is a `defer` function. This function returns a `Promise` that is resolved when all _other_ modules have been loaded.
558
+
559
+
This allows you to delay execution of the `onLoad` callback until all other modules have been loaded.
560
+
561
+
This is useful for returning contens of a module that depends on other modules.
562
+
563
+
##### Example: tracking and reporting unused exports
564
+
565
+
```ts
566
+
import { plugin } from"bun";
567
+
568
+
plugin({
569
+
name: "track imports",
570
+
setup(build) {
571
+
const transpiler =newBun.Transpiler();
572
+
573
+
let trackedImports:Record<string, number> = {};
574
+
575
+
// Each module that goes through this onLoad callback
The `onLoad` method optionally accepts a `namespace` in addition to the `filter` regex. This namespace will be be used to prefix the import in transpiled code; for instance, a loader with a `filter: /\.yaml$/` and `namespace: "yaml:"` will transform an import from `./myfile.yaml` into `yaml:./myfile.yaml`.
605
+
Note that the `.defer()` function currently has the limitation that it can only be called once per `onLoad` callback.
0 commit comments