htm preact standalone
- カテゴリ:
- JavaScript
- コメント数:
- Comments: 0
◆ htm で preact 使うなら standalone 版が htm パッケージに含まれてる
◆ バンドルしなくても unpkg からロードするだけで使える
◆ umd 版で 12 KB 程度
◆ 圧縮された通信(Brotli)では 5 KB 程度
◆ バンドルしなくても unpkg からロードするだけで使える
◆ umd 版で 12 KB 程度
◆ 圧縮された通信(Brotli)では 5 KB 程度
前回は snowpack を使うために preact と htm をそれぞれ npm からインストールしてバンドルしました
しかし htm には preact を使った standalone の JavaScript が含まれていて これだけで使えます
preact も含まれていて minify 済みのものなので unpkg などの CDN からロードするだけでいいです
今回は通常の script タグでグローバルに追加する umd を使いましたが module 版もあります
しかし htm には preact を使った standalone の JavaScript が含まれていて これだけで使えます
preact も含まれていて minify 済みのものなので unpkg などの CDN からロードするだけでいいです
サンプル
htm の preact standalone を使った例です<!doctype html>
<meta charset="utf-8" />
<script src="https://unpkg.com/htm/preact/standalone.umd.js"></script>
<script>
const {html, render, useState, useEffect} = htmPreact
const App = () => {
return html`
<h1>app</h1>
<${Component1} foo=${"ABC".repeat(10)} />
<${Component2}>code block<//>
<${Component3} />
<${Component4} />
`
}
const Component1 = (props) => {
return html`
<p>${props.foo}</p>
`
}
const Component2 = (props) => {
return html`
<pre><code>${props.children}</code></pre>
`
}
const Component3 = (props) => {
const [count, setCount] = useState(10)
return html`
<span>Count up ${"-->"}</span>
<button onclick=${() => setCount(count + 1)}>${count}</button>
`
}
const Component4 = (props) => {
const [time, setTime] = useState(new Date())
useEffect(() => {
let tid = setInterval(() => {
setTime(new Date())
}, 1000)
return () => clearInterval(tid)
})
return html`
<p>The current time is <b>${time.toLocaleString()}</b></p>
`
}
window.onload = () => render(html`<${App} />`, document.getElementById("root"))
</script>
<div id="root"></div>
今回は通常の script タグでグローバルに追加する umd を使いましたが module 版もあります
import { html, render } from "https://unpkg.com/htm/preact/standalone.module.js"