This commit is contained in:
Benjamin Toby 2026-03-05 05:50:41 +01:00
parent f7c0e927c7
commit 6dd00f2561
3 changed files with 131 additions and 5 deletions

106
CLAUDE.md Normal file
View File

@ -0,0 +1,106 @@
Default to using Bun instead of Node.js.
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
- Use `bun test` instead of `jest` or `vitest`
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
- Bun automatically loads .env, so don't use dotenv.
## APIs
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
- `Bun.redis` for Redis. Don't use `ioredis`.
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
- `WebSocket` is built-in. Don't use `ws`.
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
- Bun.$`ls` instead of execa.
## Testing
Use `bun test` to run tests.
```ts#index.test.ts
import { test, expect } from "bun:test";
test("hello world", () => {
expect(1).toBe(1);
});
```
## Frontend
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
Server:
```ts#index.ts
import index from "./index.html"
Bun.serve({
routes: {
"/": index,
"/api/users/:id": {
GET: (req) => {
return new Response(JSON.stringify({ id: req.params.id }));
},
},
},
// optional websocket support
websocket: {
open: (ws) => {
ws.send("Hello, world!");
},
message: (ws, message) => {
ws.send(message);
},
close: (ws) => {
// handle close
}
},
development: {
hmr: true,
console: true,
}
})
```
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
```html#index.html
<html>
<body>
<h1>Hello, world!</h1>
<script type="module" src="./frontend.tsx"></script>
</body>
</html>
```
With the following `frontend.tsx`:
```tsx#frontend.tsx
import React from "react";
// import .css files directly and it works
import './index.css';
import { createRoot } from "react-dom/client";
const root = createRoot(document.body);
export default function Frontend() {
return <h1>Hello, world!</h1>;
}
root.render(<Frontend />);
```
Then, run index.ts
```sh
bun --hot ./index.ts
```
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.

View File

@ -55,6 +55,10 @@ export default async function (params?: Params): Promise<ServeOptions> {
), ),
); );
return new Response(file);
} else if (url.pathname.startsWith("/favicon.")) {
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname));
return new Response(file); return new Response(file);
} else { } else {
return await handleWebPages({ req, server }); return await handleWebPages({ req, server });

View File

@ -1,12 +1,9 @@
import { watch } from "fs"; import { watch } from "fs";
import grabDirNames from "../../utils/grab-dir-names"; import grabDirNames from "../../utils/grab-dir-names";
import writeWebPageHydrationScript from "./web-pages/write-web-page-hydration-script";
import grabPageName from "../../utils/grab-page-name"; import grabPageName from "../../utils/grab-page-name";
import path from "path"; import path from "path";
import { execSync } from "child_process"; import { execSync } from "child_process";
import serverParamsGen from "./server-params-gen"; import serverParamsGen from "./server-params-gen";
import grabRouter from "../../utils/grab-router";
import type { FC } from "react";
const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, ROUTES_DIR } = const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, ROUTES_DIR } =
grabDirNames(); grabDirNames();
@ -55,9 +52,18 @@ export default function watcher() {
// }); // });
// } // }
// await Bun.build({
// entrypoints: [
// `${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx`,
// ],
// outdir: HYDRATION_DST_DIR,
// minify: true,
// });
let cmd = `bun build`; let cmd = `bun build`;
cmd += ` ${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx --outdir ${HYDRATION_DST_DIR}`; cmd += ` ${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx --outdir ${HYDRATION_DST_DIR}`;
cmd += ` --minify`; cmd += ` --minify`;
// cmd += ` && bun pm cache rm`;
execSync(cmd, { stdio: "inherit" }); execSync(cmd, { stdio: "inherit" });
@ -67,11 +73,21 @@ export default function watcher() {
}); });
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const msg = encoder.encode(`event: update\ndata: reload\n\n`); const msg = encoder.encode(
`event: update\ndata: reload\n\n`,
);
for (const controller of global.HMR_CONTROLLERS) { for (const controller of global.HMR_CONTROLLERS) {
controller.enqueue(msg); controller.enqueue(msg.toString());
} }
// Let the SSE event flush before restarting the server.
// The server restart is required to clear Bun's module cache
// so the next request renders the updated route, not the
// stale cached module (which causes a hydration mismatch).
// await Bun.sleep(500);
// await reloadServer();
global.RECOMPILING = false; global.RECOMPILING = false;
} else if (event == "rename") { } else if (event == "rename") {
await reloadServer(); await reloadServer();