Skip to content
Deploy with Vercel

与 Vercel Function 集成

¥Integration with Vercel Function

Vercel 函数默认支持 Web 标准框架,因此你无需任何额外配置即可在 Vercel 函数上运行 Elysia。

¥Vercel Function support Web Standard Framework by default, so you can run Elysia on Vercel Function without any additional configuration.

  1. 在 src/index.ts 创建一个文件
  2. 在 src/index.ts 中,创建或导入现有的 Elysia 服务器
  3. 将 Elysia 服务器导出为默认导出
typescript
import { Elysia, t } from 'elysia'

export default new Elysia()
    .get('/', () => 'Hello Vercel Function')
    .post('/', ({ body }) => body, {
        body: t.Object({
            name: t.String()
        })
    })
  1. 添加构建脚本,使用 tsdown 或类似脚本将代码打包成单个文件。
json
{
	"scripts": {
		"build": "tsdown src/index.ts -d api --dts"
	}
}
  1. 创建 vercel.json 文件,将所有端点重写到 Elysia 服务器
json
{
    "$schema": "https://openapi.vercel.sh/vercel.json",
    "rewrites": [
		{
			"source": "/(.*)",
			"destination": "/api"
		}
    ]
}

此配置会将所有请求重写到 /api 路由,Elysia 服务器就是在该路由中定义的。

¥This configuration will rewrite all requests to the /api route, which is where Elysia server is defined.

Elysia 无需额外配置即可使用 Vercel 函数,因为它默认支持 Web 标准框架。

¥No additional configuration is needed for Elysia to work with Vercel Function, as it supports the Web Standard Framework by default.

如果这不起作用

¥If this doesn't work

确保将 Elysia 服务器导出为默认导出,并且构建输出是位于 /api/index.js 中的单个文件。

¥Make sure to export the Elysia server as default export, and the build output is a single file locate in /api/index.js.

你还可以使用 Elysia 的内置功能,例如验证、错误处理、OpenAPI 等,就像在其他任何环境中一样。

¥You can also use Elysia's built-in features like validation, error handling, OpenAPI and more, just like you would in any other environment.

更多信息,请参阅 Vercel 函数文档

¥For additional information, please refer to Vercel Function documentation.