Vercel
Vercel 是前端開發人員的平台,提供創新者在靈感迸發時所需的快速性和可靠性。本節介紹在 Vercel 上運行的 Next.js。
Next.js 是一個彈性的 React 框架,為您提供構建快速 Web 應用程式的基礎模組。
在 Next.js 中,邊緣函式讓您可以在 Vercel 等邊緣執行環境上建立動態 API。使用 Hono,您可以使用與其他執行環境相同的語法編寫 API,並使用許多中介軟體。
1. 設定
Next.js 的入門範本已可用。使用 "create-hono" 命令啟動您的專案。選擇此範例的 nextjs
範本。
sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bunx create-hono my-app
sh
deno run -A npm:create-hono my-app
移動到 my-app
並安裝相依性。
sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i
2. Hello World
如果您使用 App Router,請編輯 app/api/[[...route]]/route.ts
。有關更多選項,請參閱支援的 HTTP 方法部分。
ts
import { Hono } from 'hono'
import { handle } from 'hono/vercel'
export const runtime = 'edge'
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)
如果您使用 Pages Router,請編輯 pages/api/[[...route]].ts
。
ts
import { Hono } from 'hono'
import { handle } from 'hono/vercel'
import type { PageConfig } from 'next'
export const config: PageConfig = {
runtime: 'edge',
}
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello Next.js!',
})
})
export default handle(app)
3. 執行
在本機執行開發伺服器。然後,在您的網頁瀏覽器中存取 https://127.0.0.1:3000
。
sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev
現在,/api/hello
僅返回 JSON,但是如果您建構 React UI,您可以使用 Hono 建立完整堆疊的應用程式。
4. 部署
如果您有 Vercel 帳戶,可以透過連結 Git 儲存庫來部署。
Node.js
您也可以在 Node.js 執行環境上運行的 Next.js 上執行 Hono。
首先,安裝 Node.js 轉接器。
sh
npm i @hono/node-server
接下來,您可以使用從 @hono/node-server/vercel
匯入的 handle
函式。
ts
import { Hono } from 'hono'
import { handle } from '@hono/node-server/vercel'
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 from Hono!',
})
})
export default handle(app)
為了讓此功能正常運作,請務必透過在專案儀表板或 .env
檔案中設定環境變數來停用 Vercel node.js 輔助程式
NODEJS_HELPERS=0