mcpField
H
hono-jsx

hono-jsx

github.com/bobmatnyc开发79352 次安装17 周前更新
代码仓库

关于 hono-jsx

hono-jsx 是使用 Hono 内置 JSX 渲染器进行服务端 HTML 渲染的技能,适合构建页面、模板或静态 HTML。它支持异步组件与流式输出。

主要功能

  1. 01服务端 JSX 渲染
  2. 02异步组件
  3. 03Suspense 流式输出
  4. 04自动提升 head 标签
  5. 05错误边界与 Context
  6. 06无需客户端水合

适用场景

  1. 01渲染服务端 HTML 页面
  2. 02创建邮件模板
  3. 03生成静态 HTML
  4. 04流式传输大型 HTML 响应

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill hono-jsx

安装后在 Claude Code 中输入/hono-jsx确认已加载。

附带文件metadata.json

详细介绍

Hono JSX - 服务端渲染

概述

Hono 内置 JSX 渲染器,可用于服务端 HTML 生成。它支持异步组件、使用 Suspense 进行流式传输,并可与 Hono 的响应系统无缝集成。

主要功能:

  • 服务端 JSX 渲染
  • 支持异步组件
  • 使用 Suspense 进行流式传输
  • 自动将 head 内容提升至 <head>
  • 错误边界
  • Context API
  • 无客户端水合开销

何时使用此技能

以下场景适合使用 Hono JSX:

  • 构建服务端渲染的 HTML 页面
  • 创建电子邮件模板
  • 生成静态 HTML
  • 流式传输大型 HTML 响应
  • 构建 MPA(多页应用)

不适用于:交互式 SPA(请改用 React/Vue/Svelte)

配置

TypeScript 配置
// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  }
}
替代方案:Pragma 注释
/** @jsx jsx */
/** @jsxImportSource hono/jsx */
Deno 配置
// deno.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "npm:hono/jsx"
  }
}

基本用法

简单渲染
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  return c.html(
    <html>
      <head>
        <title>Hello Hono</title>
      </head>
      <body>
        <h1>Hello, World!</h1>
      </body>
    </html>
  )
})
组件
import { Hono } from 'hono'
import type { FC } from 'hono/jsx'

// Define props type
type GreetingProps = {
  name: string
  age?: number
}

// Functional component
const Greeting: FC<GreetingProps> = ({ name, age }) => {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      {age && <p>You are {age} years old.</p>}
    </div>
  )
}

const app = new Hono()

app.get('/hello/:name', (c) => {
  const name = c.req.param('name')
  return c.html(<Greeting name={name} />)
})
布局组件
import type { FC, PropsWithChildren } from 'hono/jsx'

const Layout: FC<PropsWithChildren<{ title: string }>> = ({ title, children }) => {
  return (
    <html>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>{title}</title>
        <link rel="stylesheet" href="/styles.css" />
      </head>
      <body>
        <header>
          <nav>
            <a href="/">Home</a>
            <a href="/about">About</a>
          </nav>
        </header>
        <main>{children}</main>
        <footer>
          <p>&copy; 2025 My App</p>
        </footer>
      </body>
    </html>
  )
}

app.get('/', (c) => {
  return c.html(
    <Layout title="Home">
      <h1>Welcome!</h1>
      <p>This is my home page.</p>
    </Layout>
  )
})

异步组件

基本异步组件
const AsyncUserList: FC = async () => {
  const users = await fetchUsers()

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

app.get('/users', async (c) => {
  return c.html(<AsyncUserList />)
})
嵌套异步组件
const UserProfile: FC<{ id: string }> = async ({ id }) => {
  const user = await fetchUser(id)

  return (
    <div class="profile">
      <h2>{user.name}</h2>
      <p>{user.email}</p>
      <UserPosts userId={id} />
    </div>
  )
}

const UserPosts: FC<{ userId: string }> = async ({ userId }) => {
  const posts = await fetchUserPosts(userId)

  return (
    <div class="posts">
      <h3>Posts</h3>
      {posts.map(post => (
        <article key={post.id}>
          <h4>{post.title}</h4>
          <p>{post.excerpt}</p>
        </article>
      ))}
    </div>
  )
}

使用 Suspense 进行流式传输

基本流式传输
import { Suspense, renderToReadableStream } from 'hono/jsx/streaming'

const SlowComponent: FC = async () => {
  await new Promise(resolve => setTimeout(resolve, 2000))
  return <div>Loaded after 2 seconds!</div>
}

app.get('/stream', (c) => {
  const stream = renderToReadableStream(
    <html>
      <body>
        <h1>Streaming Demo</h1>
        <Suspense fallback={<div>Loading...</div>}>
          <SlowComponent />
        </Suspense>
      </body>
    </html>
  )

  return c.body(stream, {
    headers: {
      'Content-Type': 'text/html; charset=UTF-8',
      'Transfer-Encoding': 'chunked'
    }
  })
})
多个 Suspense 边界
const Page: FC = () => {
  return (
    <Layout title="Dashboard">
      <h1>Dashboard</h1>

      <Suspense fallback={<div>Loading user...</div>}>
        <UserProfile />
      </Suspense>

      <Suspense fallback={<div>Loading stats...</div>}>
        <Statistics />
      </Suspense>

      <Suspense fallback={<div>Loading feed...</div>}>
        <ActivityFeed />
      </Suspense>
    </Layout>
  )
}

错误边界

import { ErrorBoundary } from 'hono/jsx'

const RiskyComponent: FC = () => {
  if (Math.random() > 0.5) {
    throw new Error('Random error!')
  }
  return <div>Success!</div>
}

const ErrorFallback: FC<{ error: Error }> = ({ error }) => {
  return (
    <div class="error">
      <h3>Something went wrong</h3>
      <p>{error.message}</p>
    </div>
  )
}

app.get('/risky', (c) => {
  return c.html(
    <Layout title="Risky Page">
      <ErrorBoundary fallback={ErrorFallback}>
        <RiskyComponent />
      </ErrorBoundary>
    </Layout>
  )
})
异步错误边界
const AsyncRiskyComponent: FC = async () => {
  const data = await fetchData()

  if (!data) {
    throw new Error('Data not found')
  }

  return <div>{data}</div>
}

// Error boundary catches async errors too
<ErrorBoundary fallback={({ error }) => <p>Error: {error.message}</p>}>
  <AsyncRiskyComponent />
</ErrorBoundary>

Context API

创建 Context
import { createContext, useContext } from 'hono/jsx'

type Theme = 'light' | 'dark'

const ThemeContext = createContext<Theme>('light')

const ThemedButton: FC<{ label: string }> = ({ label }) => {
  const theme = useContext(ThemeContext)
  const className = theme === 'dark' ? 'btn-dark' : 'btn-light'

  return <button class={className}>{label}</button>
}

const App: FC<{ theme: Theme }> = ({ theme, children }) => {
  return (
    <ThemeContext.Provider value={theme}>
      <div class={`app theme-${theme}`}>
        {children}
      </div>
    </ThemeContext.Provider>
  )
}

app.get('/', (c) => {
  const theme = c.req.query('theme') as Theme || 'light'

  return c.html(
    <App theme={theme}>
      <ThemedButton label="Click me" />
    </App>
  )
})

Head 提升

<title>、<meta>、<link> 和 <script> 等标签会自动提升至 <head>:

const Page: FC<{ title: string }> = ({ title, children }) => {
  return (
    <html>
      <head>
        {/* Base head content */}
      </head>
      <body>
        {/* These will be hoisted to head! */}
        <title>{title}</title>
        <meta name="description" content="Page description" />
        <link rel="stylesheet" href="/page.css" />

        <div>{children}</div>
      </body>
    </html>
  )
}

// Even from nested components
const SEO: FC<{ title: string; description: string }> = ({ title, description }) => {
  return (
    <>
      <title>{title}</title>
      <meta name="description" content={description} />
      <meta property="og:title" content={title} />
      <meta property="og:description" content={description} />
    </>
  )
}

const Article: FC<{ article: Article }> = ({ article }) => {
  return (
    <div>
      <SEO title={article.title} description={article.excerpt} />
      <h1>{article.title}</h1>
      <div>{article.content}</div>
    </div>
  )
}

原始 HTML

dangerouslySetInnerHTML
const RawHtml: FC<{ html: string }> = ({ html }) => {
  return <div dangerouslySetInnerHTML={{ __html: html }} />
}

// Usage
const markdown = await renderMarkdown(content)
<RawHtml html={markdown} />
Raw 辅助函数
import { raw } from 'hono/html'

const Page: FC = () => {
  return (
    <html>
      <body>
        {raw('<script>console.log("Hello")</script>')}
      </body>
    </html>
  )
}

片段

import { Fragment } from 'hono/jsx'

// Using Fragment
const List: FC = () => {
  return (
    <Fragment>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </Fragment>
  )
}

// Using short syntax
const List2: FC = () => {
  return (
    <>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </>
  )
}

记忆化

import { memo } from 'hono/jsx'

// Expensive to compute
const ExpensiveComponent: FC<{ data: string[] }> = ({ data }) => {
  const processed = data.map(item => item.toUpperCase()).join(', ')
  return <div>{processed}</div>
}

// Memoize the result
const MemoizedExpensive = memo(ExpensiveComponent)

// Won't recompute if data is the same
<MemoizedExpensive data={['a', 'b', 'c']} />

集成模式

与 HTMX 集成
const TodoList: FC<{ todos: Todo[] }> = ({ todos }) => {
  return (
    <ul id="todo-list">
      {todos.map(todo => (
        <li key={todo.id}>
          <span>{todo.text}</span>
          <button
            hx-delete={`/todos/${todo.id}`}
            hx-target="closest li"
            hx-swap="outerHTML"
          >
            Delete
          </button>
        </li>
      ))}
    </ul>
  )
}

app.get('/todos', async (c) => {
  const todos = await getTodos()

  return c.html(
    <Layout title="Todos">
      <script src="https://unpkg.com/[email protected]"></script>
      <h1>Todos</h1>
      <TodoList todos={todos} />
      <form hx-post="/todos" hx-target="#todo-list" hx-swap="beforeend">
        <input name="text" placeholder="New todo" />
        <button type="submit">Add</button>
      </form>
    </Layout>
  )
})

app.post('/todos', async (c) => {
  const { text } = await c.req.parseBody()
  const todo = await createTodo(text as string)

  return c.html(
    <li>
      <span>{todo.text}</span>
      <button
        hx-delete={`/todos/${todo.id}`}
        hx-target="closest li"
        hx-swap="outerHTML"
      >
        Delete
      </button>
    </li>
  )
})
与 Tailwind CSS 集成
const Button: FC<{ variant: 'primary' | 'secondary' }> = ({ variant, children }) => {
  const baseClasses = 'px-4 py-2 rounded font-medium transition-colors'
  const variantClasses = variant === 'primary'
    ? 'bg-blue-600 text-white hover:bg-blue-700'
    : 'bg-gray-200 text-gray-800 hover:bg-gray-300'

  return (
    <button class={`${baseClasses} ${variantClasses}`}>
      {children}
    </button>
  )
}

快速参考

主要导入项
import type { FC, PropsWithChildren } from 'hono/jsx'
import { Fragment, createContext, useContext, memo } from 'hono/jsx'
import { Suspense, renderToReadableStream } from 'hono/jsx/streaming'
import { ErrorBoundary } from 'hono/jsx'
import { raw } from 'hono/html'
响应方法
// Direct render
c.html(<Component />)

// Streaming
c.body(renderToReadableStream(<Component />), {
  headers: { 'Content-Type': 'text/html; charset=UTF-8' }
})
组件类型
// Basic
const Comp: FC = () => <div>Hello</div>

// With props
const Comp: FC<{ name: string }> = ({ name }) => <div>{name}</div>

// With children
const Comp: FC<PropsWithChildren> = ({ children }) => <div>{children}</div>

// Async
const Comp: FC = async () => {
  const data = await fetch()
  return <div>{data}</div>
}

相关技能

  • hono-core - 框架基础
  • hono-middleware - 中间件模式
  • hono-cloudflare - 边缘部署

版本:Hono 4.x 最后更新:2025 年 1 月 许可证:MIT

评论

支持 Markdown