htmというpreactの作者が開発したライブラリがあり、
これを使うと、Mithrilのコンポーネントを以下のように記述できます。
簡易的なUIを素早く作りたいときに便利そうです。
import m from "https://raw.githack.com/MithrilJS/mithril.js/next/mithril.mjs";
import htm from "https://unpkg.com/htm?module";
const html = htm.bind(m);
const SearchInput = {
view(vnode) {
return html`
<div class="search-input">
<input class="search-input-text" type="search"></input>
<button class="search-input-button" onclick=${vnode.attrs.search}>🔍</button>
</div>
`;
}
};
const App = {
view(vnode) {
return html`
<${SearchInput} search=${() => alert('hoge')}><//>
`;
}
};
m.mount(document.body, App);
babel-plugin-htm
babel-plugin-htmを使うと、
htmのシンタックスをhyperscriptの呼び出しに置き換えることができます。
Mithrilで利用する際は、以下のように設定を行っておく必要があります。
.babelrc
{
"plugins": [
["htm", {
"pragma": "m"
}]
]
}
先程のコードの場合は、以下のようにコンパイルされます。
import m from "https://raw.githack.com/MithrilJS/mithril.js/next/mithril.mjs";
import htm from "https://unpkg.com/htm?module";
const html = htm.bind(m);
const SearchInput = {
view(vnode) {
return m("div", {
class: "search-input"
}, m("input", {
class: "search-input-text",
type: "search"
}), m("button", {
class: "search-input-button",
onclick: vnode.attrs.search
}, "\uD83D\uDD0D"));
}
};
const App = {
view(vnode) {
return m(SearchInput, {
search: () => alert('hoge')
});
}
};
m.mount(document.body, App);
備考
以下のバージョンで動作確認を行いました。
- htm: v2.1.1
- mithril: v2.0.0-rc4