跳转到正文

Cloudflare Pages ​

注意

对于新项目,Cloudflare 现在推荐使用 Cloudflare Workers 而非 Cloudflare Pages。Workers 支持静态资源,并提供更丰富的功能。如果要创建新的全栈应用,请参阅 Cloudflare Workers + Vite,它是本 Pages 配置的后继方案。hono/cloudflare-pages 适配器已弃用,将在 Hono v5 中移除。

Cloudflare Pages 是面向全栈 Web 应用的边缘平台。 它提供静态文件,以及由 Cloudflare Workers 提供的动态内容。

Hono 完全支持 Cloudflare Pages。 它提供了愉快的开发体验。Vite 开发服务器速度很快,使用 Wrangler 部署也非常迅速。

1. 初始化 ​

Cloudflare Pages 有可用的项目模板。 使用「create-hono」命令开始创建项目。 本示例选择 cloudflare-pages 模板。

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm 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

下面是基本的目录结构。

text
./
├── 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:

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. 运行 ​

在本地运行开发服务器,然后在浏览器中访问 http://localhost:5173。

sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev

4. 部署 ​

如果拥有 Cloudflare 账户,就可以部署到 Cloudflare。需要在 package.json 中将 $npm_execpath 改为你选择的包管理器。

sh
npm run deploy
sh
yarn deploy
sh
pnpm run deploy
sh
bun run deploy

通过 Cloudflare 控制台与 GitHub 部署 ​

  1. 登录 Cloudflare 控制台并选择你的账户。
  2. 在账户首页选择 Workers & Pages > Create application > Pages > Connect to Git。
  3. 授权 GitHub 账户并选择仓库。在 Set up builds and deployments 中填写以下信息:
配置选项值
生产分支main
构建命令npm run build
构建目录dist

绑定 ​

可以使用变量、KV、D1 等 Cloudflare 绑定。 本节将使用变量和 KV。

创建 wrangler.toml ​

首先创建 wrangler.toml,用于本地绑定:

sh
touch wrangler.toml

编辑 wrangler.toml,指定名为 MY_NAME 的变量。

toml
[vars]
MY_NAME = "Hono"

创建 KV ​

接下来创建 KV。运行以下 wrangler 命令:

sh
wrangler kv namespace create MY_KV --preview

记下以下输出中的 preview_id:

{ binding = "MY_KV", preview_id = "abcdef" }

指定 preview_id 和绑定名称 MY_KV:

toml
[[kv_namespaces]]
binding = "MY_KV"
id = "abcdef"

编辑 vite.config.ts ​

编辑 vite.config.ts:

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,并设置类型。

ts
type Bindings = {
  MY_NAME: string
  MY_KV: KVNamespace
}

const app = new Hono<{ Bindings: Bindings }>()

使用它们:

tsx
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 来判断当前是在开发服务器上运行,还是处于构建阶段。

tsx
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。

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',
        }),
      ],
    }
  }
})

可以运行以下命令构建服务端和客户端脚本。

sh
vite build --mode client && vite build

Cloudflare Pages 中间件 ​

Cloudflare Pages 使用自身的中间件系统,与 Hono 的中间件不同。可以在名为 _middleware.ts 的文件中导出 onRequest 来启用,如下所示:

ts
// functions/_middleware.ts
export async function onRequest(pagesContext) {
  console.log(`You are accessing ${pagesContext.request.url}`)
  return await pagesContext.next()
}

使用 handleMiddleware,可以将 Hono 中间件作为 Cloudflare Pages 中间件使用。

ts
// 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 基本身份验证中间件。

ts
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
import { basicAuth } from 'hono/basic-auth'

export const onRequest = handleMiddleware(
  basicAuth({
    username: 'hono',
    password: 'acoolproject',
  })
)

如果想应用多个中间件,可以这样编写:

ts
import { handleMiddleware } from 'hono/cloudflare-pages'

// ...

export const onRequest = [
  handleMiddleware(middleware1),
  handleMiddleware(middleware2),
  handleMiddleware(middleware3),
]

访问 EventContext ​

可以在 handleMiddleware 中通过 c.env 访问 EventContext 对象。

ts
// 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 访问数据值:

ts
// 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>().basePath('/api')

app.get('/hello', (c) => {
  return c.json({
    message: `Hello, ${c.env.eventContext.data.user}!`, // 'Joe'
  })
})

export const onRequest = handle(app)

基于 MIT 许可证发布。