This is the full developer documentation for Hono. # Start of Hono documentation # Hono Hono - 在日语中是火焰🔥的意思 - 是一个基于 Web 标准构建的小型、简单且超快的 Web 框架。它适用于任何 JavaScript 运行时:Cloudflare Workers、Fastly Compute、Deno、Bun、Vercel、Netlify、AWS Lambda、Lambda@Edge 和 Node.js。 ¥Hono - ***means flame🔥 in Japanese*** - is a small, simple, and ultrafast web framework built on Web Standards. It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Netlify, AWS Lambda, Lambda@Edge, and Node.js. 快速,但不仅仅是快速。 ¥Fast, but not only fast. ```ts twoslash import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hono!')) export default app ``` ## 快速入门 ¥Quick Start 只需运行这个: ¥Just run this: ::: code-group ```sh [npm] npm create hono@latest ``` ```sh [yarn] yarn create hono ``` ```sh [pnpm] pnpm create hono@latest ``` ```sh [bun] bun create hono@latest ``` ```sh [deno] deno init --npm hono@latest ``` ::: ## 功能 ¥Features * 超快 🚀 - 路由 `RegExpRouter` 非常快。不使用线性循环。快速。 ¥**Ultrafast** 🚀 - The router `RegExpRouter` is really fast. Not using linear loops. Fast. * 轻量级 🪶 - `hono/tiny` 预设小于 14kB。Hono 没有任何依赖,仅使用 Web 标准。 ¥**Lightweight** 🪶 - The `hono/tiny` preset is under 14kB. Hono has zero dependencies and uses only the Web Standards. * 多运行时 🌍 - 适用于 Cloudflare Workers、Fastly Compute、Deno、Bun、AWS Lambda 或 Node.js。相同的代码在所有平台上运行。 ¥**Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, AWS Lambda, or Node.js. The same code runs on all platforms. * 包含适配 🔋 - Hono 具有内置中间件、自定义中间件、第三方中间件和助手。包含适配。 ¥**Batteries Included** 🔋 - Hono has built-in middleware, custom middleware, third-party middleware, and helpers. Batteries included. * Delightful DX 😃 - 超级干净的 API。一流的 TypeScript 支持。现在,我们得到了 "类型"。 ¥**Delightful DX** 😃 - Super clean APIs. First-class TypeScript support. Now, we've got "Types". ## 用例 ¥Use-cases Hono 是一个类似于 Express 的简单 Web 应用框架,没有前端。但它在 CDN Edges 上运行,并允许你与中间件结合使用时构建更大的应用。以下是一些用例示例。 ¥Hono is a simple web application framework similar to Express, without a frontend. But it runs on CDN Edges and allows you to construct larger applications when combined with middleware. Here are some examples of use-cases. * 构建 Web API ¥Building Web APIs * 后端服务器的代理 ¥Proxy of backend servers * CDN 前端 ¥Front of CDN * Edge 应用 ¥Edge application * 库的基本服务器 ¥Base server for a library * 全栈应用 ¥Full-stack application ## 谁在使用 Hono? ¥Who is using Hono? | 项目 | 平台 | 用于什么? | | ---------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------- | | [cdnjs](https://cdnjs.com) | Cloudflare Workers | 免费开源 CDN 服务。Hono 用于 API 服务器。 | | [Cloudflare D1](https://www.cloudflare.com/developer-platform/d1/) | Cloudflare Workers | 无服务器 SQL 数据库。Hono 用于内部 API 服务器。 | | [Cloudflare Workers KV](https://www.cloudflare.com/developer-platform/workers-kv/) | Cloudflare Workers | 无服务器键值数据库。Hono 用于内部 API 服务器。 | | [BaseAI](https://baseai.dev) | 本地 AI 服务器 | 带内存的无服务器 AI 代理管道。一个用于 Web 的开源代理 AI 框架。带有 Hono 的 API 服务器。 | | [Unkey](https://unkey.dev) | Cloudflare Workers | 一个开源 API 身份验证和授权。Hono 用于 API 服务器。 | | [OpenStatus](https://openstatus.dev) | Bun | 一个开源网站和 API 监控平台。Hono 用于 API 服务器。 | | [Deno 基准测试](https://deno.com/benchmarks) | Deno | 基于 V8 构建的安全 TypeScript 运行时。Hono 用于基准测试。 | | [Clerk](https://clerk.com) | Cloudflare Workers | 一个开源用户管理平台。Hono 用于 API 服务器。 | 以及以下内容。 ¥And the following. * [Drivly](https://driv.ly/) - Cloudflare Workers * [repeat.dev](https://repeat.dev/) - Cloudflare Workers 你想看更多吗?参见 [谁在生产中使用 Hono?](https://github.com/orgs/honojs/discussions/1510)。 ¥Do you want to see more? See [Who is using Hono in production?](https://github.com/orgs/honojs/discussions/1510). ## 1 分钟内掌握 Hono ¥Hono in 1 minute 使用 Hono 为 Cloudflare Workers 创建应用的演示。 ¥A demonstration to create an application for Cloudflare Workers with Hono. ![A gif showing a hono app being created quickly with fast iteration.](/images/sc.gif) ## 超快 ¥Ultrafast 与 Cloudflare Workers 的其他路由相比,Hono 是最快的。 ¥**Hono is the fastest**, compared to other routers for Cloudflare Workers. ``` Hono x 402,820 ops/sec ±4.78% (80 runs sampled) itty-router x 212,598 ops/sec ±3.11% (87 runs sampled) sunder x 297,036 ops/sec ±4.76% (77 runs sampled) worktop x 197,345 ops/sec ±2.40% (88 runs sampled) Fastest is Hono ✨ Done in 28.06s. ``` 参见 [更多基准](/docs/concepts/benchmarks)。 ¥See [more benchmarks](/docs/concepts/benchmarks). ## 轻量级 ¥Lightweight Hono 很小。使用 `hono/tiny` 预设,其大小在最小化时低于 14KB。有许多中间件和适配器,但它们仅在使用时打包在一起。有关上下文,Express 的大小为 572KB。 ¥**Hono is so small**. With the `hono/tiny` preset, its size is **under 14KB** when minified. There are many middleware and adapters, but they are bundled only when used. For context, the size of Express is 572KB. ``` $ npx wrangler dev --minify ./src/index.ts ⛅️ wrangler 2.20.0 -------------------- ⬣ Listening at http://0.0.0.0:8787 - http://127.0.0.1:8787 - http://192.168.128.165:8787 Total Upload: 11.47 KiB / gzip: 4.34 KiB ``` ## 多个路由 ¥Multiple routers Hono 有多个路由。 ¥**Hono has multiple routers**. RegExpRouter 是 JavaScript 世界中最快的路由。它使用在调度之前创建的单个大型正则表达式来匹配路由。使用 SmartRouter,它支持所有路由模式。 ¥**RegExpRouter** is the fastest router in the JavaScript world. It matches the route using a single large Regex created before dispatch. With **SmartRouter**, it supports all route patterns. LinearRouter 可以非常快速地注册路由,因此它适用于每次初始化应用的环境。PatternRouter 只是添加和匹配模式,使其变小。 ¥**LinearRouter** registers the routes very quickly, so it's suitable for an environment that initializes applications every time. **PatternRouter** simply adds and matches the pattern, making it small. 参见 [有关路由的更多信息](/docs/concepts/routers)。 ¥See [more information about routes](/docs/concepts/routers). ## Web 标准 ¥Web Standards 由于使用了 Web 标准,Hono 可以在很多平台上运行。 ¥Thanks to the use of the **Web Standards**, Hono works on a lot of platforms. * Cloudflare Workers * Cloudflare 页面 ¥Cloudflare Pages * Fastly 计算 ¥Fastly Compute * Deno * Bun * Vercel * AWS Lambda * Lambda@Edge * 其他 ¥Others 通过使用 [Node.js 适配器](https://github.com/honojs/node-server),Hono 可以在 Node.js 上运行。 ¥And by using [a Node.js adapter](https://github.com/honojs/node-server), Hono works on Node.js. 参见 [有关 Web 标准的更多信息](/docs/concepts/web-standard)。 ¥See [more information about Web Standards](/docs/concepts/web-standard). ## 中间件和助手 ¥Middleware & Helpers Hono 有许多中间件和助手。这使 "写得少,做得多" 成为现实。 ¥**Hono has many middleware and helpers**. This makes "Write Less, do more" a reality. 开箱即用,Hono 提供中间件和助手: ¥Out of the box, Hono provides middleware and helpers for: * [基本身份验证](/docs/middleware/builtin/basic-auth) ¥[Basic Authentication](/docs/middleware/builtin/basic-auth) * [承载身份验证](/docs/middleware/builtin/bearer-auth) ¥[Bearer Authentication](/docs/middleware/builtin/bearer-auth) * [主体限制](/docs/middleware/builtin/body-limit) ¥[Body Limit](/docs/middleware/builtin/body-limit) * [缓存](/docs/middleware/builtin/cache) ¥[Cache](/docs/middleware/builtin/cache) * [压缩](/docs/middleware/builtin/compress) ¥[Compress](/docs/middleware/builtin/compress) * [上下文存储](/docs/middleware/builtin/context-storage) ¥[Context Storage](/docs/middleware/builtin/context-storage) * [Cookie](/docs/helpers/cookie) * [CORS](/docs/middleware/builtin/cors) * [ETag](/docs/middleware/builtin/etag) * [html](/docs/helpers/html) * [JSX](/docs/guides/jsx) * [JWT 身份验证](/docs/middleware/builtin/jwt) ¥[JWT Authentication](/docs/middleware/builtin/jwt) * [日志器](/docs/middleware/builtin/logger) ¥[Logger](/docs/middleware/builtin/logger) * [语言](/docs/middleware/builtin/language) ¥[Language](/docs/middleware/builtin/language) * [漂亮的 JSON](/docs/middleware/builtin/pretty-json) ¥[Pretty JSON](/docs/middleware/builtin/pretty-json) * [安全标头](/docs/middleware/builtin/secure-headers) ¥[Secure Headers](/docs/middleware/builtin/secure-headers) * [SSG](/docs/helpers/ssg) * [流式传输](/docs/helpers/streaming) ¥[Streaming](/docs/helpers/streaming) * [GraphQL 服务器](https://github.com/honojs/middleware/tree/main/packages/graphql-server) ¥[GraphQL Server](https://github.com/honojs/middleware/tree/main/packages/graphql-server) * [Firebase 身份验证](https://github.com/honojs/middleware/tree/main/packages/firebase-auth) ¥[Firebase Authentication](https://github.com/honojs/middleware/tree/main/packages/firebase-auth) * [Sentry](https://github.com/honojs/middleware/tree/main/packages/sentry) * 其他! ¥Others! 例如,使用 Hono 添加 ETag 和请求日志记录只需要几行代码: ¥For example, adding ETag and request logging only takes a few lines of code with Hono: ```ts import { Hono } from 'hono' import { etag } from 'hono/etag' import { logger } from 'hono/logger' const app = new Hono() app.use(etag(), logger()) ``` 参见 [有关中间件的更多信息](/docs/concepts/middleware)。 ¥See [more information about Middleware](/docs/concepts/middleware). ## 开发者体验 ¥Developer Experience Hono 提供了令人愉悦的 "开发者体验"。 ¥Hono provides a delightful "**Developer Experience**". 借助 `Context` 对象,可以轻松访问请求/响应。此外,Hono 是用 TypeScript 编写的。Hono 有 "类型"。 ¥Easy access to Request/Response thanks to the `Context` object. Moreover, Hono is written in TypeScript. Hono has "**Types**". 例如,路径参数将是字面量类型。 ¥For example, the path parameters will be literal types. ![A screenshot showing Hono having proper literal typing when URL parameters. The URL "/entry/:date/:id" allows for request parameters to be "date" or "id"](/images/ss.png) Validator 和 Hono Client `hc` 启用了 RPC 模式。在 RPC 模式下,你可以使用自己喜欢的验证器(例如 Zod),并轻松地与客户端共享服务器端 API 规范并构建类型安全的应用。 ¥And, the Validator and Hono Client `hc` enable the RPC mode. In RPC mode, you can use your favorite validator such as Zod and easily share server-side API specs with the client and build type-safe applications. 参见 [Hono Stacks](/docs/concepts/stacks)。 ¥See [Hono Stacks](/docs/concepts/stacks). # SSG 助手 ¥SSG Helper SSG Helper 从你的 Hono 应用生成静态站点。它将检索已注册路由的内容并将其保存为静态文件。 ¥SSG Helper generates a static site from your Hono application. It will retrieve the contents of registered routes and save them as static files. ## 用法 ¥Usage ### 手动 ¥Manual 如果你有一个简单的 Hono 应用,如下所示: ¥If you have a simple Hono application like the following: ```tsx // index.tsx const app = new Hono() app.get('/', (c) => c.html('Hello, World!')) app.use('/about', async (c, next) => { c.setRenderer((content, head) => { return c.html( {head.title ?? ''}

{content}

) }) await next() }) app.get('/about', (c) => { return c.render('Hello!', { title: 'Hono SSG Page' }) }) export default app ``` 对于 Node.js,创建如下构建脚本: ¥For Node.js, create a build script like this: ```ts // build.ts import app from './index' import { toSSG } from 'hono/ssg' import fs from 'fs/promises' toSSG(app, fs) ``` 通过执行脚本,文件将输出如下: ¥By executing the script, the files will be output as follows: ```bash ls ./static about.html index.html ``` ### Vite 插件 ¥Vite Plugin 使用 `@hono/vite-ssg` Vite 插件,你可以轻松处理该过程。 ¥Using the `@hono/vite-ssg` Vite Plugin, you can easily handle the process. 有关更多详细信息,请参见此处: ¥For more details, see here: [https://github.com/honojs/vite-plugins/tree/main/packages/ssg](https://github.com/honojs/vite-plugins/tree/main/packages/ssg) ## toSSG `toSSG` 是生成静态站点的主要函数,以应用和文件系统模块作为参数。它基于以下内容: ¥`toSSG` is the main function for generating static sites, taking an application and a filesystem module as arguments. It is based on the following: ### 输入 ¥Input toSSG 的参数在 ToSSGInterface 中指定。 ¥The arguments for toSSG are specified in ToSSGInterface. ```ts export interface ToSSGInterface { ( app: Hono, fsModule: FileSystemModule, options?: ToSSGOptions ): Promise } ``` * `app` 指定已注册路由的 `new Hono()`。 ¥`app` specifies `new Hono()` with registered routes. * `fs` 指定以下对象,假设 `node:fs/promise`。 ¥`fs` specifies the following object, assuming `node:fs/promise`. ```ts export interface FileSystemModule { writeFile(path: string, data: string | Uint8Array): Promise mkdir( path: string, options: { recursive: boolean } ): Promise } ``` ### 使用 Deno 和 Bun 的适配器 ¥Using adapters for Deno and Bun 如果要在 Deno 或 Bun 上使用 SSG,则每个文件系统都提供了一个 `toSSG` 函数。 ¥If you want to use SSG on Deno or Bun, a `toSSG` function is provided for each file system. 对于 Deno: ¥For Deno: ```ts import { toSSG } from 'hono/deno' toSSG(app) // The second argument is an option typed `ToSSGOptions`. ``` 对于 Bun: ¥For Bun: ```ts import { toSSG } from 'hono/bun' toSSG(app) // The second argument is an option typed `ToSSGOptions`. ``` ### 选项 ¥Options 选项在 ToSSGOptions 接口中指定。 ¥Options are specified in the ToSSGOptions interface. ```ts export interface ToSSGOptions { dir?: string concurrency?: number extensionMap?: Record plugins?: SSGPlugin[] } ``` * `dir` 是静态文件的输出目标。默认值为 `./static`。 ¥`dir` is the output destination for Static files. The default value is `./static`. * `concurrency` 是同时生成的文件数。默认值为 `2`。 ¥`concurrency` is the concurrent number of files to be generated at the same time. The default value is `2`. * `extensionMap` 是一个映射,其中包含 `Content-Type` 作为键和扩展字符串作为值。这用于确定输出文件的文件扩展名。 ¥`extensionMap` is a map containing the `Content-Type` as a key and the string of the extension as a value. This is used to determine the file extension of the output file. * `plugins` 是一个 SSG 插件数组,用于扩展静态站点生成过程的功能。 ¥`plugins` is an array of SSG plugins that extend the functionality of the static site generation process. ### 输出 ¥Output `toSSG` 以以下 Result 类型返回结果。 ¥`toSSG` returns the result in the following Result type. ```ts export interface ToSSGResult { success: boolean files: string[] error?: Error } ``` ## 生成文件 ¥Generate File ### 路由和文件名 ¥Route and Filename 以下规则适用于注册的路由信息​​和生成的文件名。默认 `./static` 的行为如下: ¥The following rules apply to the registered route information and the generated file name. The default `./static` behaves as follows: * `/` -> `./static/index.html` * `/path` -> `./static/path.html` * `/path/` -> `./static/path/index.html` ### 文件扩展名 ¥File Extension 文件扩展名取决于每个路由返回的 `Content-Type`。例如,来自 `c.html` 的响应保存为 `.html`。 ¥The file extension depends on the `Content-Type` returned by each route. For example, responses from `c.html` are saved as `.html`. 如果你想要自定义文件扩展名,请设置 `extensionMap` 选项。 ¥If you want to customize the file extensions, set the `extensionMap` option. ```ts import { toSSG, defaultExtensionMap } from 'hono/ssg' // Save `application/x-html` content with `.html` toSSG(app, fs, { extensionMap: { 'application/x-html': 'html', ...defaultExtensionMap, }, }) ``` 请注意,无论扩展名是什么,以斜杠结尾的路径都会保存为 index.ext。 ¥Note that paths ending with a slash are saved as index.ext regardless of the extension. ```ts // save to ./static/html/index.html app.get('/html/', (c) => c.html('html')) // save to ./static/text/index.txt app.get('/text/', (c) => c.text('text')) ``` ## 中间件 ¥Middleware 引入支持 SSG 的内置中间件。 ¥Introducing built-in middleware that supports SSG. ### ssgParams 你可以使用 Next.js 的 `generateStaticParams` 之类的 API。 ¥You can use an API like `generateStaticParams` of Next.js. 示例: ¥Example: ```ts app.get( '/shops/:id', ssgParams(async () => { const shops = await getShops() return shops.map((shop) => ({ id: shop.id })) }), async (c) => { const shop = await getShop(c.req.param('id')) if (!shop) { return c.notFound() } return c.render(

{shop.name}

) } ) ``` ### disableSSG 具有 `disableSSG` 中间件集的路由被 `toSSG` 排除在静态文件生成之外。 ¥Routes with the `disableSSG` middleware set are excluded from static file generation by `toSSG`. ```ts app.get('/api', disableSSG(), (c) => c.text('an-api')) ``` ### onlySSG 具有 `onlySSG` 中间件集的路由将在 `toSSG` 执行后被 `c.notFound()` 覆盖。 ¥Routes with the `onlySSG` middleware set will be overridden by `c.notFound()` after `toSSG` execution. ```ts app.get('/static-page', onlySSG(), (c) => c.html(

Welcome to my site

)) ``` ## 插件 ¥Plugins 插件允许你扩展静态站点生成过程的功能。它们使用钩子在不同阶段自定义生成过程。 ¥Plugins allow you to extend the functionality of the static site generation process. They use hooks to customize the generation process at different stages. ### 默认插件 ¥Default Plugin 默认情况下,`toSSG` 使用 `defaultPlugin`,它会跳过非 200 状态响应(例如重定向、错误或 404)。这可以防止为不成功的响应生成文件。 ¥By default, `toSSG` uses `defaultPlugin` which skips non-200 status responses (like redirects, errors, or 404s). This prevents generating files for unsuccessful responses. ```ts import { toSSG, defaultPlugin } from 'hono/ssg' // defaultPlugin is automatically applied when no plugins specified toSSG(app, fs) // Equivalent to: toSSG(app, fs, { plugins: [defaultPlugin] }) ``` 如果你指定了自定义插件,`defaultPlugin` 不会自动包含在内。要在添加自定义插件时保留默认行为,请明确包含它: ¥If you specify custom plugins, `defaultPlugin` is **not** automatically included. To keep the default behavior while adding custom plugins, explicitly include it: ```ts toSSG(app, fs, { plugins: [defaultPlugin, myCustomPlugin], }) ``` ### 钩子类型 ¥Hook Types 插件可以使用以下钩子来自定义 `toSSG` 流程: ¥Plugins can use the following hooks to customize the `toSSG` process: ```ts export type BeforeRequestHook = (req: Request) => Request | false export type AfterResponseHook = (res: Response) => Response | false export type AfterGenerateHook = ( result: ToSSGResult ) => void | Promise ``` * BeforeRequestHook:处理每个请求前调用。返回 `false` 可跳过路由。 ¥**BeforeRequestHook**: Called before processing each request. Return `false` to skip the route. * AfterResponseHook:收到每个响应后调用。返回 `false` 可跳过文件生成。 ¥**AfterResponseHook**: Called after receiving each response. Return `false` to skip file generation. * AfterGenerateHook:整个生成过程完成后调用。 ¥**AfterGenerateHook**: Called after the entire generation process completes. ### 插件界面 ¥Plugin Interface ```ts export interface SSGPlugin { beforeRequestHook?: BeforeRequestHook | BeforeRequestHook[] afterResponseHook?: AfterResponseHook | AfterResponseHook[] afterGenerateHook?: AfterGenerateHook | AfterGenerateHook[] } ``` ### 基本插件示例 ¥Basic Plugin Examples 仅过滤 GET 请求: ¥Filter only GET requests: ```ts const getOnlyPlugin: SSGPlugin = { beforeRequestHook: (req) => { if (req.method === 'GET') { return req } return false }, } ``` 按状态码过滤: ¥Filter by status code: ```ts const statusFilterPlugin: SSGPlugin = { afterResponseHook: (res) => { if (res.status === 200 || res.status === 500) { return res } return false }, } ``` 日志生成的文件: ¥Log generated files: ```ts const logFilesPlugin: SSGPlugin = { afterGenerateHook: (result) => { if (result.files) { result.files.forEach((file) => console.log(file)) } }, } ``` ### 高级插件示例 ¥Advanced Plugin Example 以下是创建生成 `sitemap.xml` 文件的站点地图插件的示例: ¥Here's an example of creating a sitemap plugin that generates a `sitemap.xml` file: ```ts // plugins.ts import fs from 'node:fs/promises' import path from 'node:path' import type { SSGPlugin } from 'hono/ssg' import { DEFAULT_OUTPUT_DIR } from 'hono/ssg' export const sitemapPlugin = (baseURL: string): SSGPlugin => { return { afterGenerateHook: (result, fsModule, options) => { const outputDir = options?.dir ?? DEFAULT_OUTPUT_DIR const filePath = path.join(outputDir, 'sitemap.xml') const urls = result.files.map((file) => new URL(file, baseURL).toString() ) const siteMapText = ` ${urls.map((url) => `${url}`).join('\n')} ` fsModule.writeFile(filePath, siteMapText) }, } } ``` 应用插件: ¥Applying plugins: ```ts import app from './index' import { toSSG } from 'hono/ssg' import { sitemapPlugin } from './plugins' toSSG(app, fs, { plugins: [ getOnlyPlugin, statusFilterPlugin, logFilesPlugin, sitemapPlugin('https://example.com'), ], }) ``` # 接受助手 ¥Accepts Helper Accepts Helper 有助于处理请求中的 Accept 标头。 ¥Accepts Helper helps to handle Accept headers in the Requests. ## 导入 ¥Import ```ts import { Hono } from 'hono' import { accepts } from 'hono/accepts' ``` ## `accepts()` `accepts()` 函数查看 Accept 标头,例如 Accept-Encoding 和 Accept-Language,并返回正确的值。 ¥The `accepts()` function looks at the Accept header, such as Accept-Encoding and Accept-Language, and returns the proper value. ```ts import { accepts } from 'hono/accepts' app.get('/', (c) => { const accept = accepts(c, { header: 'Accept-Language', supports: ['en', 'ja', 'zh'], default: 'en', }) return c.json({ lang: accept }) }) ``` ### `AcceptHeader` 类型 ¥`AcceptHeader` type `AcceptHeader` 类型的定义如下。 ¥The definition of the `AcceptHeader` type is as follows. ```ts export type AcceptHeader = | 'Accept' | 'Accept-Charset' | 'Accept-Encoding' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Post' | 'Accept-Ranges' ``` ## 选项 ¥Options ### 标头:`AcceptHeader` ¥ header: `AcceptHeader` 目标接受标头。 ¥The target accept header. ### <徽章类型="danger" 文本="required" /> 支持:`string[]` ¥ supports: `string[]` 你的应用支持的标头值。 ¥The header values which your application supports. ### 默认:`string` ¥ default: `string` 默认值。 ¥The default values. ### match:`(accepts: Accept[], config: acceptsConfig) => string` 自定义匹配函数。 ¥The custom match function. # css 助手 ¥css Helper css 助手 - `hono/css` - 是 Hono 在 JS(X) 中内置的 CSS。 ¥The css helper - `hono/css` - is Hono's built-in CSS in JS(X). 你可以在名为 `css` 的 JavaScript 模板字面量中以 JSX 形式编写 CSS。`css` 的返回值将是类名,它设置为类属性的值。然后 ` {title}
{children}
) }) ``` ## `keyframes` ¥`keyframes` 你可以使用 `keyframes` 写入 `@keyframes` 的内容。在这种情况下,`fadeInAnimation` 将是动画的名称 ¥You can use `keyframes` to write the contents of `@keyframes`. In this case, `fadeInAnimation` will be the name of the animation ```tsx const fadeInAnimation = keyframes` from { opacity: 0; } to { opacity: 1; } ` const headerClass = css` animation-name: ${fadeInAnimation}; animation-duration: 2s; ` const Header = () => Hello! ``` ## `cx` ¥`cx` `cx` 组合了两个类名。 ¥The `cx` composites the two class names. ```tsx const buttonClass = css` border-radius: 10px; ` const primaryClass = css` background: orange; ` const Button = () => ( Click! ) ``` 它还可以编写简单的字符串。 ¥It can also compose simple strings. ```tsx const Header = () => Hi ``` ## 与 [安全标头](/docs/middleware/builtin/secure-headers) 中间件结合使用 ¥Usage in combination with [Secure Headers](/docs/middleware/builtin/secure-headers) middleware 如果要将 css 助手与 [安全标头](/docs/middleware/builtin/secure-headers) 中间件结合使用,可以将 [`nonce` 属性](https://web.nodejs.cn/en-US/docs/Web/HTML/Global_attributes/nonce) 添加到 `