Cloudflare Pages
Cloudflare Pages 是一個用於全端 Web 應用程式的邊緣平台。它提供靜態檔案和 Cloudflare Workers 提供的動態內容。
Hono 完全支援 Cloudflare Pages。它帶來令人愉悅的開發者體驗。Vite 的開發伺服器速度很快,而且使用 Wrangler 部署也非常快速。
1. 設定
Cloudflare Pages 的入門範本可用。使用「create-hono」命令開始您的專案。在這個範例中,選擇 cloudflare-pages
範本。
npm create hono@latest my-app
yarn create hono my-app
pnpm create hono my-app
bunx create-hono my-app
deno run -A npm:create-hono my-app
移動到 my-app
並安裝相依性。
cd my-app
npm i
cd my-app
yarn
cd my-app
pnpm i
cd my-app
bun i
以下是基本的目錄結構。
./
├── package.json
├── public
│ └── static // Put your static files.
│ └── style.css // You can refer to it as `/static/style.css`.
├── src
│ ├── index.tsx // The entry point for server-side.
│ └── renderer.tsx
├── tsconfig.json
└── vite.config.ts
2. Hello World
像下面這樣編輯 src/index.tsx
import { Hono } from 'hono'
import { renderer } from './renderer'
const app = new Hono()
app.get('*', renderer)
app.get('/', (c) => {
return c.render(<h1>Hello, Cloudflare Pages!</h1>)
})
export default app
3. 執行
在本地執行開發伺服器。然後,在您的 Web 瀏覽器中存取 https://127.0.0.1:5173
。
npm run dev
yarn dev
pnpm dev
bun run dev
4. 部署
如果您有 Cloudflare 帳戶,您可以部署到 Cloudflare。在 package.json
中,$npm_execpath
需要更改為您選擇的套件管理器。
npm run deploy
yarn deploy
pnpm run deploy
bun run deploy
透過 GitHub 使用 Cloudflare 儀表板部署
- 登入 Cloudflare 儀表板 並選擇您的帳戶。
- 在帳戶首頁中,選擇 Workers & Pages > 建立應用程式 > Pages > 連線到 Git。
- 授權您的 GitHub 帳戶,並選擇存放庫。在設定建置和部署中,提供以下資訊
組態選項 | 值 |
---|---|
正式環境分支 | main |
建置命令 | npm run build |
建置目錄 | dist |
繫結
您可以使用 Cloudflare 繫結,例如變數、KV、D1 和其他。在本節中,讓我們使用變數和 KV。
建立 wrangler.toml
首先,建立用於本地繫結的 wrangler.toml
touch wrangler.toml
編輯 wrangler.toml
。使用名稱 MY_NAME
指定變數。
[vars]
MY_NAME = "Hono"
建立 KV
接下來,建立 KV。執行以下 wrangler
命令
wrangler kv namespace create MY_KV --preview
記下 preview_id
,如下列輸出所示
{ binding = "MY_KV", preview_id = "abcdef" }
使用繫結名稱 MY_KV
指定 preview_id
[[kv_namespaces]]
binding = "MY_KV"
id = "abcdef"
編輯 vite.config.ts
編輯 vite.config.ts
import devServer from '@hono/vite-dev-server'
import adapter from '@hono/vite-dev-server/cloudflare'
import build from '@hono/vite-cloudflare-pages'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
devServer({
entry: 'src/index.tsx',
adapter, // Cloudflare Adapter
}),
build(),
],
})
在您的應用程式中使用繫結
在您的應用程式中使用變數和 KV。設定類型。
type Bindings = {
MY_NAME: string
MY_KV: KVNamespace
}
const app = new Hono<{ Bindings: Bindings }>()
使用它們
app.get('/', async (c) => {
await c.env.MY_KV.put('name', c.env.MY_NAME)
const name = await c.env.MY_KV.get('name')
return c.render(<h1>Hello! {name}</h1>)
})
在正式環境中
對於 Cloudflare Pages,您將使用 wrangler.toml
進行本地開發,但對於正式環境,您將在儀表板中設定繫結。
客戶端
您可以使用 Vite 的功能編寫客戶端腳本並將其匯入您的應用程式。如果 /src/client.ts
是客戶端的進入點,只需將其寫在 script 標籤中即可。此外,import.meta.env.PROD
對於偵測它是在開發伺服器上執行還是在建置階段執行非常有用。
app.get('/', (c) => {
return c.html(
<html>
<head>
{import.meta.env.PROD ? (
<script type='module' src='/static/client.js'></script>
) : (
<script type='module' src='/src/client.ts'></script>
)}
</head>
<body>
<h1>Hello</h1>
</body>
</html>
)
})
為了正確建置腳本,您可以使用如下所示的範例組態檔 vite.config.ts
。
import pages from '@hono/vite-cloudflare-pages'
import devServer from '@hono/vite-dev-server'
import { defineConfig } from 'vite'
export default defineConfig(({ mode }) => {
if (mode === 'client') {
return {
build: {
rollupOptions: {
input: './src/client.ts',
output: {
entryFileNames: 'static/client.js',
},
},
},
}
} else {
return {
plugins: [
pages(),
devServer({
entry: 'src/index.tsx',
}),
],
}
}
})
您可以執行以下命令來建置伺服器和客戶端腳本。
vite build --mode client && vite build
Cloudflare Pages 中介軟體
Cloudflare Pages 使用其自己的 中介軟體 系統,該系統與 Hono 的中介軟體不同。您可以透過在名為 _middleware.ts
的檔案中匯出 onRequest
來啟用它,如下所示
// functions/_middleware.ts
export async function onRequest(pagesContext) {
console.log(`You are accessing ${pagesContext.request.url}`)
return await pagesContext.next()
}
使用 handleMiddleware
,您可以將 Hono 的中介軟體用作 Cloudflare Pages 中介軟體。
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
export const onRequest = handleMiddleware(async (c, next) => {
console.log(`You are accessing ${c.req.url}`)
await next()
})
您也可以使用 Hono 的內建中介軟體和第三方中介軟體。例如,要新增基本身份驗證,您可以使用Hono 的基本身份驗證中介軟體。
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
import { basicAuth } from 'hono/basic-auth'
export const onRequest = handleMiddleware(
basicAuth({
username: 'hono',
password: 'acoolproject',
})
)
如果您想套用多個中介軟體,您可以這樣寫
import { handleMiddleware } from 'hono/cloudflare-pages'
// ...
export const onRequest = [
handleMiddleware(middleware1),
handleMiddleware(middleware2),
handleMiddleware(middleware3),
]
存取 EventContext
您可以在 handleMiddleware
中透過 c.env
存取 EventContext
物件。
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
export const onRequest = [
handleMiddleware(async (c, next) => {
c.env.eventContext.data.user = 'Joe'
await next()
}),
]
然後,您可以透過處理程式中的 c.env.eventContext
存取資料值
// functions/api/[[route]].ts
import type { EventContext } from 'hono/cloudflare-pages'
import { handle } from 'hono/cloudflare-pages'
// ...
type Env = {
Bindings: {
eventContext: EventContext
}
}
const app = new Hono<Env>()
app.get('/hello', (c) => {
return c.json({
message: `Hello, ${c.env.eventContext.data.user}!`, // 'Joe'
})
})
export const onRequest = handle(app)