Appearance
Next.js
Next.js 是一个灵活的 React 框架,它为你提供构建快速 Web 应用的构建块。
🌐 Next.js is a flexible React framework that gives you building blocks to create fast web applications.
当使用 Node.js 运行时,你可以在 Next.js 上运行 Hono。在 Vercel 上,通过使用 Vercel 函数,部署带 Next.js 的 Hono 很容易。
🌐 You can run Hono on Next.js when using the Node.js runtime.
On Vercel, deploying Hono with Next.js is easy by using Vercel Functions.
1. 设置
🌐 1. Setup
Next.js 的入门模板已可用。使用 "create-hono" 命令启动你的项目。此示例请选择 nextjs 模板。
🌐 A starter for Next.js is available. Start your project with "create-hono" command. Select nextjs template for this example.
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 并安装依赖。
🌐 Move into my-app and install the dependencies.
sh
cd my-app
npm ish
cd my-app
yarnsh
cd my-app
pnpm ish
cd my-app
bun i2. 你好,世界
🌐 2. Hello World
如果你使用应用路由,请编辑 app/api/[[...route]]/route.ts。有关更多选项,请参考支持的 HTTP 方法部分。
🌐 If you use the App Router, Edit app/api/[[...route]]/route.ts. Refer to the Supported HTTP Methods section for more options.
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)
export const POST = handle(app)3. 跑
🌐 3. Run
在本地运行开发服务器。然后,在你的网页浏览器中访问 http://localhost:3000。
🌐 Run the development server locally. Then, access http://localhost:3000 in your Web browser.
sh
npm run devsh
yarn devsh
pnpm devsh
bun run dev现在,/api/hello 只是返回 JSON,但如果你构建 React 界面,你可以用 Hono 创建一个全栈应用。
🌐 Now, /api/hello just returns JSON, but if you build React UIs, you can create a full-stack application with Hono.
4. 部署
🌐 4. Deploy
如果你拥有 Vercel 账户,则可以通过链接 Git 仓库进行部署。
🌐 If you have a Vercel account, you can deploy by linking the Git repository.
页面路由
🌐 Pages Router
如果你使用 Pages Router,则需要先安装 Node.js 适配器。
🌐 If you use the Pages Router, you'll need to install the Node.js adapter first.
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 函数。
🌐 Then, you can utilize the getRequestListener function imported from @hono/node-server in pages/api/[[...route]].ts.
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 助手。
🌐 In order for this to work with the Pages Router, it's important to disable Vercel Node.js helpers by setting up an environment variable in your project dashboard or in your .env file.
text
NODEJS_HELPERS=0