JSXでHTML文字列を生成
動機
HTMLをベタ打ちするのがだるい
JSXでcomponent分割しつつ、型推論が効いた状態で楽に書きたい
調査
Reactの場合
renderToStaticMarkup()を使う
References
テンプレートエンジンに React を使いつつ、きれいな HTML を生成したいんじゃ!!
How to generate static HTML using React, TypeScript, and Node.js - SaltyCrane Blog
文字列から実行時に変換する
https://zenn.dev/rosylilly/articles/202105-react-jsx-renderer
react-jsx-renderer
react-jsx-parser
Preactの場合
preact-render-to-stringを使う
preact-render-to-stringで試してみる
code:jsx
/** @jsx h */
import {renderToString} from "https://scrapbox.io/api/code/takker/preact-render-to-string@5.1.19/mod.js";
import { h } from "https://scrapbox.io/api/code/takker/preact@10.5.14/mod.js";
const Charset = () => <meta charset="utf-8" />;
const Head = ({title}) => <head><Charset /><title>{title}</title></head>;
const Body = () => (
<body>
<h1>Heading 1</h1>
<p>
テスト文字列
</p>
</body>
);
const App = () => (
<html>
<Head title="Hello, World!"/>
<Body />
</html>
);
console.log(renderToString(<App />, {}, { pretty: true }));
まあこんなもんか
JSXからHTMLへの返還だけなら簡単だ
ただし、ScrapHTMLEditorのような、更新されるたびにHTMLをrenderし直す用途には難しいかも
毎回全てのJSXをrenderしなければならない
差分更新が出来ない
毎度esbuildでゼロからbuild & Function()で実行するのを繰り返すしかなさそう
performanceの問題は、適当にthrottleで間引いて解決させるしかない
表現をより簡潔にするには、こうかな?
JSXをほぼベタ打ちできるようにする
hとrenderToStringのimport構文を不要にする
最終的にrenderしたいJSXをdefault exportする
code:example.tsx
const Body = () => <body />
export default = (<html>
<head />
<Body />
</html>)
esbuildでHTMLに変換する
その際、pluginか何かでhなどのimportとrenderToString()によるrenderingを追加する
jsx pramgaも設定する
出来たHTMLは<iframe>に読ませるなり別タブで開くなりする
#2023-01-10 22:24:16
#2021-09-17 13:09:24