在 Vercel 上部署 Bun 应用
Vercel 是一个用于构建、部署和扩展应用的云平台。Vercel Functions 可以在 Bun 运行时上运行,可以通过 Vercel 支持的框架运行,也可以作为 Bun.serve() 服务器运行。
- 在 vercel.json 中配置 Bun
要在 Bun 上运行 Functions,请将
bunVersion字段添加到vercel.json文件中:vercel.json{ "bunVersion": "1.4.x" // [!code ++] }Vercel 会管理补丁版本。
为获得最佳效果,请确保本地 Bun 版本与 Vercel 使用的版本一致。
- 添加服务器
选择请求到达代码的方式。
Vercel 的 Bun 框架预设会将部署的每个请求发送到单个
Bun.serve()服务器。当项目设置了bunVersion、包含bun.lock文件,并且在以下路径之一存在服务器入口点时,Vercel 会使用该预设:server.{js,cjs,mjs,ts,cts,mts}src/server.{js,cjs,mjs,ts,cts,mts}
在 Bun 1.2 或更高版本中,
bun install会创建bun.lock。在旧版本中,请运行bun install --save-text-lockfile。该预设不会检测二进制格式的bun.lockb。在模块加载时调用一次
Bun.serve()。Vercel 会检测到该调用,并将传入请求路由到它。Vercel 支持fetch、routes、error和websocket选项:server.ts
Bun.serve({ routes: { "/health": () => Response.json({ status: "ok" }), }, fetch() { return new Response("Hello from Bun on Vercel"); }, });最小项目包含
package.json、bun.lock、server.ts以及上一步中的vercel.json。它不需要api/目录或任何路由配置。要将 Bun 服务器添加到同时包含前端的项目中,请创建
api/server.ts,并在模块加载时调用一次Bun.serve()。Vercel 会将其作为/api/server下的单个 Function 部署。与框架预设不同,只有针对/api/server的请求才会到达此服务器。api/server.ts
Bun.serve({ fetch(request) { const url = new URL(request.url); return Response.json({ message: "Hello from Bun on Vercel", pathname: url.pathname, }); }, });此设置只需要上一步中的
bunVersion配置;它不会使用框架预设,也不要求存在bun.lock文件。若要将其他路径发送到此服务器,请在vercel.json中添加路由覆盖规则。每个覆盖规则都必须使用完整请求路径,包括/api/server前缀。详情请参阅 Vercel Bun 运行时文档。Vercel 支持的框架(例如 Next.js、Express、Hono 和 Nitro)在设置
bunVersion后即可在 Bun 上运行。如果你要部署 Next.js 项目(包括 ISR),还需要更新
package.json中的脚本,使 Next.js CLI 在 Bun 下运行:package.json{ "scripts": { "dev": "bun --bun next dev", // [!code ++] "build": "bun --bun next build" // [!code ++] } } - 部署你的应用
将你的代码库连接至 Vercel,或通过 CLI 进行部署:
terminal# 使用 bunx(无全局安装) bunx vercel login bunx vercel deploy或者全局安装 Vercel CLI:
terminalbun i -g vercel vercel login vercel deploy - 验证运行时
要确认你的部署使用了 Bun,可以打印 Bun 版本:
server.ts
console.log("runtime", process.versions.bun);Textruntime 1.4.0
- Fluid 计算:Bun 和 Node.js 运行时均运行在 Fluid 计算上,并支持相同的核心 Vercel Functions 功能。
- 中间件:若要使用 Bun 运行路由中间件,需要将运行时设置为
nodejs:
export const config = { runtime: "nodejs" }; // [!code ++]