在 node.js 使用 jsx 做为 html 模板

248 阅读1分钟
// filename: newsletter.tsx

import { jsxToHtml } from '@incremental-html/jsx-to-html'// server is an express routerserver.get('/newsletter', async (req, resp) => {     const html: string = await jsxToHtml(<div>hello</div>);    resp.status(200).set({ 'Content-Type': 'text/html' }).end(html);})

需要修改 tsconfig.json 来翻译 jsx:

{    "compilerOptions": {//...        "jsx": "react",        "jsxFactory": "jsxToHtml.createElement",        "jsxFragmentFactory": "jsxToHtml.Fragment",//...}

异步上下文

node.js `async_hooks` 可以传递上下文。但是在 deno,cloudflare workers 等环境下是没有的。jsx-to-html 的异步上下文不依赖 node.js,它可以在异步函数之间自动传递 context 对象

test('component with context', async () => {    const C1 = async (props: {}, ctx: { msg: string }) => {        await new Promise<void>(resolve => resolve());        return <div>{ctx.msg}</div>    }    const result = <context msg="hello"><C1 /></context>    expect(await jsxToHtml(result, { msg: 'original msg' })).toBe('<div>\nhello\n</div>');})

对 C1 的调用并没有显式传参,context 对象是自动传进去的。

`` 是一个内置的组件,用来设置和修改上下文。

源代码: github.com/taowen/incr…