image cache on cloudflare r2
1
2Default to using Bun instead of Node.js.
3
4- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
5- Use `bun test` instead of `jest` or `vitest`
6- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
7- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
8- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
9- Use `bunx <package> <command>` instead of `npx <package> <command>`
10- Bun automatically loads .env, so don't use dotenv.
11
12## APIs
13
14- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
15- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
16- `Bun.redis` for Redis. Don't use `ioredis`.
17- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
18- `WebSocket` is built-in. Don't use `ws`.
19- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
20- Bun.$`ls` instead of execa.
21
22## Testing
23
24Use `bun test` to run tests.
25
26```ts#index.test.ts
27import { test, expect } from "bun:test";
28
29test("hello world", () => {
30 expect(1).toBe(1);
31});
32```
33
34## Frontend
35
36Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
37
38Server:
39
40```ts#index.ts
41import index from "./index.html"
42
43Bun.serve({
44 routes: {
45 "/": index,
46 "/api/users/:id": {
47 GET: (req) => {
48 return new Response(JSON.stringify({ id: req.params.id }));
49 },
50 },
51 },
52 // optional websocket support
53 websocket: {
54 open: (ws) => {
55 ws.send("Hello, world!");
56 },
57 message: (ws, message) => {
58 ws.send(message);
59 },
60 close: (ws) => {
61 // handle close
62 }
63 },
64 development: {
65 hmr: true,
66 console: true,
67 }
68})
69```
70
71HTML 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.
72
73```html#index.html
74<html>
75 <body>
76 <h1>Hello, world!</h1>
77 <script type="module" src="./frontend.tsx"></script>
78 </body>
79</html>
80```
81
82With the following `frontend.tsx`:
83
84```tsx#frontend.tsx
85import React from "react";
86import { createRoot } from "react-dom/client";
87
88// import .css files directly and it works
89import './index.css';
90
91const root = createRoot(document.body);
92
93export default function Frontend() {
94 return <h1>Hello, world!</h1>;
95}
96
97root.render(<Frontend />);
98```
99
100Then, run index.ts
101
102```sh
103bun --hot ./index.ts
104```
105
106For more information, read the Bun API docs in `node_modules/bun-types/docs/**.mdx`.