JSX
使用 hono/jsx 可以用 JSX 语法编写 HTML。
虽然 hono/jsx 也能在客户端运行,但它最常见的使用场景仍是服务端渲染。本章介绍在服务端与客户端共同适用的 JSX 相关要点。
配置
要启用 JSX,请修改 tsconfig.json:
tsconfig.json:
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx"
}
}或者使用编译指示:
/** @jsx jsx */
/** @jsxImportSource hono/jsx */如果使用 Deno,则需要修改 deno.json 而不是 tsconfig.json:
{
"compilerOptions": {
"jsx": "precompile",
"jsxImportSource": "hono/jsx"
}
}用法
INFO
如果你刚刚完成快速上手,默认生成的入口文件扩展名为 .ts——需要将其改为 .tsx,否则无法运行应用。同时别忘了更新 package.json(或 Deno 用户需修改 deno.json)以匹配新的入口文件,例如将开发脚本中的 bun run --hot src/index.ts 改成 bun run --hot src/index.tsx。
index.tsx:
import { Hono } from 'hono'
import type { FC } from 'hono/jsx'
const app = new Hono()
const Layout: FC = (props) => {
return (
<html>
<body>{props.children}</body>
</html>
)
}
const Top: FC<{ messages: string[] }> = (props: {
messages: string[]
}) => {
return (
<Layout>
<h1>Hello Hono!</h1>
<ul>
{props.messages.map((message) => {
return <li>{message}!!</li>
})}
</ul>
</Layout>
)
}
app.get('/', (c) => {
const messages = ['Good Morning', 'Good Evening', 'Good Night']
return c.html(<Top messages={messages} />)
})
export default app元数据提升
你可以在组件中直接书写 <title>、<link>、<meta> 等文档元数据标签。框架会自动将这些标签提升到文档的 <head> 区域。对于 <head> 元素距离实际决定元数据的组件较远的情况,这一点尤为便利。
import { Hono } from 'hono'
const app = new Hono()
app.use('*', async (c, next) => {
c.setRenderer((content) => {
return c.html(
<html>
<head></head>
<body>{content}</body>
</html>
)
})
await next()
})
app.get('/about', (c) => {
return c.render(
<>
<title>About Page</title>
<meta name='description' content='This is the about page.' />
about page content
</>
)
})
export default appFragment
使用 Fragment 可以在不增加额外节点的情况下包裹多个元素:
import { Fragment } from 'hono/jsx'
const List = () => (
<Fragment>
<p>first child</p>
<p>second child</p>
<p>third child</p>
</Fragment>
)如果配置正确,也可以写成 <></>。
const List = () => (
<>
<p>first child</p>
<p>second child</p>
<p>third child</p>
</>
)PropsWithChildren
使用 PropsWithChildren 可以在函数组件中正确推断子元素类型。
import { PropsWithChildren } from 'hono/jsx'
type Post = {
id: number
title: string
}
function Component({ title, children }: PropsWithChildren<Post>) {
return (
<div>
<h1>{title}</h1>
{children}
</div>
)
}插入原始 HTML
如果需要直接插入 HTML,可以使用 dangerouslySetInnerHTML:
app.get('/foo', (c) => {
const inner = { __html: 'JSX · SSR' }
const Div = <div dangerouslySetInnerHTML={inner} />
})记忆化
通过 memo 记忆化生成的字符串,可以优化组件性能:
import { memo } from 'hono/jsx'
const Header = memo(() => <header>Welcome to Hono</header>)
const Footer = memo(() => <footer>Powered by Hono</footer>)
const Layout = (
<div>
<Header />
<p>Hono is cool!</p>
<Footer />
</div>
)Context
使用 useContext 可以在组件树的任意层级共享数据,无需逐层传递 props。
import type { FC } from 'hono/jsx'
import { createContext, useContext } from 'hono/jsx'
const themes = {
light: {
color: '#000000',
background: '#eeeeee',
},
dark: {
color: '#ffffff',
background: '#222222',
},
}
const ThemeContext = createContext(themes.light)
const Button: FC = () => {
const theme = useContext(ThemeContext)
return <button style={theme}>Push!</button>
}
const Toolbar: FC = () => {
return (
<div>
<Button />
</div>
)
}
// ...
app.get('/', (c) => {
return c.html(
<div>
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
</div>
)
})异步组件
hono/jsx 支持异步组件,因此可以在组件中使用 async/await。当你使用 c.html() 渲染时,会自动等待异步结果。
const AsyncComponent = async () => {
await new Promise((r) => setTimeout(r, 1000)) // 延迟 1 秒
return <div>Done!</div>
}
app.get('/', (c) => {
return c.html(
<html>
<body>
<AsyncComponent />
</body>
</html>
)
})Suspense 实验性
提供了类似 React 的 Suspense 功能。 将异步组件包裹在 Suspense 中时,会先渲染备用内容(fallback),待 Promise 解析后再显示真实内容。你可以结合 renderToReadableStream() 使用。
import { renderToReadableStream, Suspense } from 'hono/jsx/streaming'
//...
app.get('/', (c) => {
const stream = renderToReadableStream(
<html>
<body>
<Suspense fallback={<div>loading...</div>}>
<Component />
</Suspense>
</body>
</html>
)
return c.body(stream, {
headers: {
'Content-Type': 'text/html; charset=UTF-8',
'Transfer-Encoding': 'chunked',
},
})
})ErrorBoundary 实验性
使用 ErrorBoundary 可以捕获子组件中的错误。
在下例中,如果抛出错误,就会展示 fallback 指定的内容。
function SyncComponent() {
throw new Error('Error')
return <div>Hello</div>
}
app.get('/sync', async (c) => {
return c.html(
<html>
<body>
<ErrorBoundary fallback={<div>Out of Service</div>}>
<SyncComponent />
</ErrorBoundary>
</body>
</html>
)
})ErrorBoundary 也可以与异步组件及 Suspense 搭配使用。
async function AsyncComponent() {
await new Promise((resolve) => setTimeout(resolve, 2000))
throw new Error('Error')
return <div>Hello</div>
}
app.get('/with-suspense', async (c) => {
return c.html(
<html>
<body>
<ErrorBoundary fallback={<div>Out of Service</div>}>
<Suspense fallback={<div>Loading...</div>}>
<AsyncComponent />
</Suspense>
</ErrorBoundary>
</body>
</html>
)
})StreamingContext 实验性
StreamingContext 可用于为 Suspense、ErrorBoundary 等流式组件提供配置。例如在生成的 <script> 标签上添加 CSP 所需的 nonce 值。
import { Suspense, StreamingContext } from 'hono/jsx/streaming'
// ...
app.get('/', (c) => {
const stream = renderToReadableStream(
<html>
<body>
<StreamingContext
value={{ scriptNonce: 'random-nonce-value' }}
>
<Suspense fallback={<div>Loading...</div>}>
<AsyncComponent />
</Suspense>
</StreamingContext>
</body>
</html>
)
return c.body(stream, {
headers: {
'Content-Type': 'text/html; charset=UTF-8',
'Transfer-Encoding': 'chunked',
'Content-Security-Policy':
"script-src 'nonce-random-nonce-value'",
},
})
})scriptNonce 会自动附加到由 Suspense 与 ErrorBoundary 组件生成的 <script> 标签上。
与 html 中间件集成
将 JSX 与 html 中间件结合,可以更高效地构建页面模板。更多细节请查看 html 中间件文档。
import { Hono } from 'hono'
import { html } from 'hono/html'
const app = new Hono()
interface SiteData {
title: string
children?: any
}
const Layout = (props: SiteData) =>
html`<!doctype html>
<html>
<head>
<title>${props.title}</title>
</head>
<body>
${props.children}
</body>
</html>`
const Content = (props: { siteData: SiteData; name: string }) => (
<Layout {...props.siteData}>
<h1>Hello {props.name}</h1>
</Layout>
)
app.get('/:name', (c) => {
const { name } = c.req.param()
const props = {
name: name,
siteData: {
title: 'JSX with html sample',
},
}
return c.html(<Content {...props} />)
})
export default app配合 JSX 渲染器中间件
通过 JSX 渲染器中间件,可以更轻松地使用 JSX 构建 HTML 页面。
覆盖类型定义
你可以覆盖类型定义以添加自定义元素与属性。
declare module 'hono/jsx' {
namespace JSX {
interface IntrinsicElements {
'my-custom-element': HTMLAttributes & {
'x-event'?: 'click' | 'scroll'
}
}
}
}