diff options
Diffstat (limited to 'docs/runtime/hot.md')
-rw-r--r-- | docs/runtime/hot.md | 38 |
1 files changed, 4 insertions, 34 deletions
diff --git a/docs/runtime/hot.md b/docs/runtime/hot.md index 0797187de..7f0b04c28 100644 --- a/docs/runtime/hot.md +++ b/docs/runtime/hot.md @@ -102,55 +102,25 @@ Traditional file watchers like `nodemon` restart the entire process, so HTTP ser Bun provides the following simplified API for implementing HTTP servers. Refer to [API > HTTP](/docs/api/http) for full details. ```ts#server.ts -import {type Serve} from "bun"; +import {serve} from "bun"; globalThis.count ??= 0; globalThis.count++; -export default { +serve({ fetch(req: Request) { return new Response(`Reloaded ${globalThis.count} times`); }, port: 3000, -} satisfies Serve; +}); ``` The file above is simply exporting an object with a `fetch` handler defined. When this file is executed, Bun interprets this as an HTTP server and passes the exported object into `Bun.serve`. -Unlike an explicit call to `Bun.serve`, the object-based syntax works out of the box with `bun --hot`. When you save the file, your HTTP server be reloaded with the updated code without the process being restarted. This results in seriously fast refresh speeds. +When you save the file, your HTTP server be reloaded with the updated code without the process being restarted. This results in seriously fast refresh speeds. {% image src="https://user-images.githubusercontent.com/709451/195477632-5fd8a73e-014d-4589-9ba2-e075ad9eb040.gif" alt="Bun vs Nodemon refresh speeds" caption="Bun on the left, Nodemon on the right." /%} -For more fine-grained control, you can use the `Bun.serve` API directly and handle the server reloading manually. - -```ts#server.ts -import type {Serve, Server} from "bun"; - -// make TypeScript happy -declare global { - var count: number; - var server: Server; -} - -globalThis.count ??= 0; -globalThis.count++; - -// define server parameters -const serverOptions: Serve = { - port: 3000, - fetch(req) { - return new Response(`Reloaded ${globalThis.count} times`); - } -}; - -if (!globalThis.server) { - globalThis.server = Bun.serve(serverOptions); -} else { - // reload server - globalThis.server.reload(serverOptions); -} -``` - {% callout %} **Note** — In a future version of Bun, support for Vite's `import.meta.hot` is planned to enable better lifecycle management for hot reloading and to align with the ecosystem. |