0
1

More than 5 years have passed since last update.

htmを使ってMithrilのコンポーネントをJSXライクに記述する

Last updated at Posted at 2019-05-03

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

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1