Bun
Bun 是另一个 JavaScript 运行时。它不是 Node.js 或 Deno。Bun 内置了 Trans Compiler,因此我们可以直接用 TypeScript 编写代码。Hono 也可以运行在 Bun 上。
1. 安装 Bun
要安装 bun
命令,请参考 官方文档 提供的说明。
2. 初始化项目
2.1. 新建项目
Bun 提供了 Starter 模板。通过 bun create
命令创建项目。本示例选择 bun
模板。
bun create hono@latest my-app
进入 my-app
目录并安装依赖。
cd my-app
bun install
2.2. 在已有项目中使用
如果已有 Bun 项目,只需在项目根目录安装 hono
依赖即可:
bun add hono
3. Hello World
“Hello World” 示例与其他平台几乎一致。
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))
export default app
4. 运行
执行以下命令:
bun run dev
然后在浏览器访问 http://localhost:3000
。
修改端口号
可以通过导出 port
来指定端口号。
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))
export default {
port: 3000,
fetch: app.fetch,
}
提供静态文件
要提供静态文件,可使用从 hono/bun
导入的 serveStatic
。
import { serveStatic } from 'hono/bun'
const app = new Hono()
app.use('/static/*', serveStatic({ root: './' }))
app.use('/favicon.ico', serveStatic({ path: './favicon.ico' }))
app.get('/', (c) => c.text('You can access: /static/hello.txt'))
app.get('*', serveStatic({ path: './static/fallback.txt' }))
上述代码适配如下目录结构:
./
├── favicon.ico
├── src
└── static
├── demo
│ └── index.html
├── fallback.txt
├── hello.txt
└── images
└── dinotocat.png
rewriteRequestPath
如果想把 http://localhost:3000/static/*
映射到 ./statics
,可以使用 rewriteRequestPath
选项:
app.get(
'/static/*',
serveStatic({
root: './',
rewriteRequestPath: (path) =>
path.replace(/^\/static/, '/statics'),
})
)
mimes
可以通过 mimes
添加 MIME 类型:
app.get(
'/static/*',
serveStatic({
mimes: {
m3u8: 'application/vnd.apple.mpegurl',
ts: 'video/mp2t',
},
})
)
onFound
可使用 onFound
在文件找到时进行处理:
app.get(
'/static/*',
serveStatic({
onFound: (_path, c) => {
c.header('Cache-Control', `public, immutable, max-age=31536000`)
},
})
)
onNotFound
可使用 onNotFound
在文件未找到时进行处理:
app.get(
'/static/*',
serveStatic({
onNotFound: (path, c) => {
console.log(`${path} is not found, you access ${c.req.path}`)
},
})
)
precompressed
precompressed
选项会检查 .br
或 .gz
等压缩文件,并根据 Accept-Encoding
优先返回 Brotli、Zstd、Gzip 压缩文件。如果都不存在,则返回原始文件。
app.get(
'/static/*',
serveStatic({
precompressed: true,
})
)
测试
Bun 提供 bun:test
用于测试。
import { describe, expect, it } from 'bun:test'
import app from '.'
describe('My first test', () => {
it('Should return 200 Response', async () => {
const req = new Request('http://localhost/')
const res = await app.fetch(req)
expect(res.status).toBe(200)
})
})
然后运行测试命令:
bun test index.test.ts