Next.js
Next.js 是一个灵活的 React 框架,提供构建快速 Web 应用所需的基础组件。
使用 Node.js 运行时时,可以在 Next.js 上运行 Hono。
在 Vercel 上,使用 Vercel Functions 可以轻松部署结合 Next.js 的 Hono 应用。
1. 初始化
Next.js 有可用的项目模板。 使用「create-hono」命令开始创建项目。 本示例选择 nextjs 模板。
sh
npm create hono@latest my-appsh
yarn create hono my-appsh
pnpm create hono my-appsh
bun create hono@latest my-appsh
deno init --npm hono my-app进入 my-app 并安装依赖。
sh
cd my-app
npm ish
cd my-app
yarnsh
cd my-app
pnpm ish
cd my-app
bun i2. Hello World
如果使用 App Router,请编辑 app/api/[[...route]]/route.ts。更多选项请参阅支持的 HTTP 方法部分。
ts
import { Hono } from 'hono'
import { handle } from '@hono/vercel'
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello Next.js!',
})
})
export const GET = handle(app)
`handle` comes from the `@hono/vercel` package, which the starter installs. On an existing project, add it with `npm i @hono/vercel`.
export const POST = handle(app)3. 运行
在本地运行开发服务器,然后在浏览器中访问 http://localhost:3000。
sh
npm run devsh
yarn devsh
pnpm devsh
bun run dev目前 /api/hello 仅返回 JSON;如果构建 React 界面,就可以使用 Hono 创建全栈应用。
4. 部署
如果拥有 Vercel 账户,可以通过关联 Git 仓库进行部署。
Pages Router
如果使用 Pages Router,需要先安装 Node.js 适配器。
sh
npm i @hono/node-serversh
yarn add @hono/node-serversh
pnpm add @hono/node-serversh
bun add @hono/node-server然后在 pages/api/[[...route]].ts 中使用从 @hono/node-server 导入的 getRequestListener 函数。
ts
import { getRequestListener } from '@hono/node-server'
import { Hono } from 'hono'
import type { PageConfig } from 'next'
export const config: PageConfig = {
api: {
bodyParser: false,
},
}
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello Next.js!',
})
})
export default getRequestListener(app.fetch)为了使其在 Pages Router 中正常工作,必须在项目控制台或 .env 文件中设置环境变量,禁用 Vercel Node.js 辅助函数。
text
NODEJS_HELPERS=0