Skip to content

Bun

Bun 是另一种 JavaScript 运行时。它不是 Node.js 也不是 Deno。Bun 包含一个转译器,因此我们可以用 TypeScript 或普通的 JavaScript 编写代码。Hono 也可以在 Bun 上运行。

1. 安装 Bun

🌐 1. Install Bun

要安装 bun 命令,请按照 官方网站 的说明操作。

🌐 To install bun command, follow the instruction in the official web site.

2. 设置

🌐 2. Setup

2.1. 设置一个新项目

🌐 2.1. Setup a new project

Bun 的入门模板可用。使用 “bun create” 命令开始你的项目。 在此示例中选择 bun 模板。

🌐 A starter for Bun is available. Start your project with "bun create" command. Select bun template for this example.

sh
bun create hono@latest my-app

移入 my-app 并安装依赖。

🌐 Move into my-app and install the dependencies.

sh
cd my-app
bun install

2.2. 设置现有项目

🌐 2.2. Setup an existing project

在现有的 Bun 项目中,我们只需要通过在项目根目录安装 hono 依赖

🌐 On an existing Bun project, we only need to install hono dependencies on the project root directory via

sh
bun add hono

然后将 dev 命令添加到现有的 package.json 中。

🌐 Then add the dev command to your existing package.json.

json
{
  "scripts": {
    "dev": "bun run --hot src/index.ts"
  }
}

请参阅 Bun 启动模板 以获取一个最小示例设置。这是运行 bun create hono@latest 的输出。

🌐 See the Bun starter template for a minimal example setup. This is the output of running bun create hono@latest.

3. 你好,世界

🌐 3. Hello World

“Hello World” 脚本如下。几乎和在其他平台上编写的一样。

ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))

export default app

如果你在现有项目中设置 Hono,bun run dev 命令期望将“Hello World”脚本放置在 src/index.ts

🌐 If you are setting up Hono on an existing project, the bun run dev command expects the "Hello World" script to be placed in src/index.ts

4. 跑

🌐 4. Run

运行命令。

🌐 Run the command.

sh
bun run dev

然后,在你的浏览器中访问 http://localhost:3000

🌐 Then, access http://localhost:3000 in your browser.

更改端口编号

🌐 Change port number

你可以通过导出 port 来指定端口号。

🌐 You can specify the port number with exporting the port.

ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))

export default app 
export default { 
  port: 3000, 
  fetch: app.fetch, 
} 

提供静态文件

🌐 Serve static files

要提供静态文件,使用从 hono/bun 导入的 serveStatic

🌐 To serve static files, use serveStatic which is imported from hono/bun.

ts
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' }))

对于上述代码,它将与以下目录结构配合良好。

🌐 For the above code, it will work well with the following directory structure.

./
├── favicon.ico
├── src
└── static
    ├── demo
    │   └── index.html
    ├── fallback.txt
    ├── hello.txt
    └── images
        └── dinotocat.png

rewriteRequestPath

如果你想将 http://localhost:3000/static/* 映射到 ./statics,你可以使用 rewriteRequestPath 选项:

🌐 If you want to map http://localhost:3000/static/* to ./statics, you can use the rewriteRequestPath option:

ts
app.get(
  '/static/*',
  serveStatic({
    root: './',
    rewriteRequestPath: (path) =>
      path.replace(/^\/static/, '/statics'),
  })
)

mimes

你可以使用 mimes 添加 MIME 类型:

🌐 You can add MIME types with mimes:

ts
app.get(
  '/static/*',
  serveStatic({
    mimes: {
      m3u8: 'application/vnd.apple.mpegurl',
      ts: 'video/mp2t',
    },
  })
)

onFound

当找到请求的文件时,你可以使用 onFound 指定处理方式:

🌐 You can specify handling when the requested file is found with onFound:

ts
app.get(
  '/static/*',
  serveStatic({
    // ...
    onFound: (_path, c) => {
      c.header('Cache-Control', `public, immutable, max-age=31536000`)
    },
  })
)

onNotFound

你可以使用 onNotFound 指定在未找到请求的文件时的处理方式:

🌐 You can specify handling when the requested file is not found with onNotFound:

ts
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。如果都不可用,则提供原始文件。

🌐 The precompressed option checks if files with extensions like .br or .gz are available and serves them based on the Accept-Encoding header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file.

ts
app.get(
  '/static/*',
  serveStatic({
    precompressed: true,
  })
)

测试

🌐 Testing

你可以在 Bun 上使用 bun:test 进行测试。

🌐 You can use bun:test for testing on Bun.

ts
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)
  })
})

然后,运行命令。

🌐 Then, run the command.

sh
bun test index.test.ts

Hono 中文网 - 粤ICP备13048890号