Adapter 助手
Adapter 助手通过统一的接口,让你可以无缝访问不同平台。
导入
ts
import { Hono } from 'hono'
import { env, getRuntimeKey } from 'hono/adapter'env()
env() 函数用于在不同运行时中获取环境变量,适用范围不仅限于 Cloudflare Workers 的 Bindings。env(c) 返回的值会随着运行时而有所不同。
ts
import { env } from 'hono/adapter'
app.get('/env', (c) => {
// 在 Node.js 或 Bun 中,NAME 对应 process.env.NAME
// 在 Cloudflare 中,NAME 来自 `wrangler.toml`
const { NAME } = env<{ NAME: string }>(c)
return c.text(NAME)
})支持的运行时、无服务器平台与云服务:
- Cloudflare Workers
wrangler.tomlwrangler.jsonc
- Deno
Deno.env.env文件
- Bun
Bun.envprocess.env
- Node.js
process.env
- Vercel
- AWS Lambda
- Lambda@Edge
Lambda 不支持在 Lambda@Edge 中使用环境变量,你需要改用 Lambda@Edge 事件。 - Fastly Compute
在 Fastly Compute 中,可以通过 ConfigStore 管理自定义数据。 - Netlify
在 Netlify 中,可以使用 Netlify Contexts 管理自定义数据。
指定运行时
你可以将运行时键作为第二个参数传入,以便从指定的运行时读取环境变量。
ts
app.get('/env', (c) => {
const { NAME } = env<{ NAME: string }>(c, 'workerd')
return c.text(NAME)
})getRuntimeKey()
getRuntimeKey() 函数会返回当前运行时的标识符。
ts
app.get('/', (c) => {
if (getRuntimeKey() === 'workerd') {
return c.text('You are on Cloudflare')
} else if (getRuntimeKey() === 'bun') {
return c.text('You are on Bun')
}
...
})可用的运行时键
以下列出了可用的运行时键。尚未支持的运行时可能会被标记为 other,部分键名参考了 WinterCG 的 Runtime Keys 提案。
workerd- Cloudflare Workersdenobunnodeedge-light- Vercel Edge Functionsfastly- Fastly Computeother- 其他未知运行时键