htmxとは
htmxは、HTMLの属性だけでAJAXリクエスト、CSSトランジション、WebSocketなどを実現するライブラリです。JavaScriptを書かずにインタラクティブなWebアプリケーションを構築できます。
htmx 2.0の新機能
サイズの削減
htmx 1.x: 14KB (gzip)
htmx 2.0: 10KB (gzip)
新しい属性
<!-- hx-disabled-elt: リクエスト中に要素を無効化 -->
<button hx-post="/api/submit"
hx-disabled-elt="this">
送信
</button>
<!-- hx-on: イベントハンドラをより簡潔に -->
<div hx-on:htmx:after-request="alert('完了!')">
...
</div>
<!-- hx-inherit: 継承の制御 -->
<div hx-boost="true">
<a href="/page" hx-inherit="false">
ブーストを無効化
</a>
</div>
基本的な使い方
AJAXリクエスト
<!-- GETリクエスト -->
<button hx-get="/api/users" hx-target="#user-list">
ユーザー一覧を取得
</button>
<div id="user-list"></div>
<!-- POSTリクエスト -->
<form hx-post="/api/users" hx-target="#result">
<input name="name" placeholder="名前">
<input name="email" placeholder="メール">
<button type="submit">登録</button>
</form>
<div id="result"></div>
トリガーのカスタマイズ
<!-- 入力時に検索(デバウンス付き) -->
<input type="search"
name="q"
hx-get="/search"
hx-trigger="input changed delay:300ms"
hx-target="#search-results">
<!-- スクロールで追加読み込み -->
<div hx-get="/api/posts?page=2"
hx-trigger="revealed"
hx-swap="afterend">
Loading...
</div>
スワップ戦略
<!-- 内部を置換(デフォルト) -->
<div hx-get="/content" hx-swap="innerHTML">
<!-- 要素全体を置換 -->
<div hx-get="/content" hx-swap="outerHTML">
<!-- 末尾に追加 -->
<div hx-get="/content" hx-swap="beforeend">
<!-- トランジション付き -->
<div hx-get="/content" hx-swap="innerHTML transition:true">
サーバーサイドとの連携
Expressの例
app.get('/api/users', (req, res) => {
const users = getUsers();
// HTMLを直接返す
res.send(`
<ul>
${users.map(u => `<li>${u.name}</li>`).join('')}
</ul>
`);
});
// HX-Trigger ヘッダーでイベントを発火
app.post('/api/users', (req, res) => {
const user = createUser(req.body);
res.setHeader('HX-Trigger', 'userCreated');
res.send(`<p>ユーザー ${user.name} を作成しました</p>`);
});
Go (Echo) の例
e.POST("/api/todos", func(c echo.Context) error {
todo := createTodo(c.FormValue("title"))
c.Response().Header().Set("HX-Trigger", "todoAdded")
return c.HTML(200, fmt.Sprintf(
`<li>%s</li>`, todo.Title,
))
})
拡張機能
WebSocket
<script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script>
<div hx-ext="ws" ws-connect="/chat">
<div id="messages"></div>
<form ws-send>
<input name="message">
<button>送信</button>
</form>
</div>
Server-Sent Events
<script src="https://unpkg.com/htmx.org/dist/ext/sse.js"></script>
<div hx-ext="sse" sse-connect="/events">
<div sse-swap="message">
イベントを待機中...
</div>
</div>
View Transitions API対応
<meta name="htmx-config" content='{"globalViewTransitions": true}'>
<style>
::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 0.3s;
}
</style>
いつhtmxを使うべきか
✓ サーバーサイドレンダリング中心のアプリ
✓ シンプルなインタラクション
✓ プログレッシブエンハンスメント
✓ JavaScriptを最小限にしたい
✗ 複雑なクライアント状態管理
✗ オフライン対応が必要
✗ リッチなUIコンポーネント
まとめ
htmx 2.0は、HTMLの拡張だけでインタラクティブなWebアプリケーションを構築できる軽量ライブラリです。サーバーサイドレンダリングとの相性が良く、シンプルなアプリケーションでは複雑なJavaScriptフレームワークの代替となります。
← 一覧に戻る