lit-html を IE で動かす
- カテゴリ:
- JavaScript
- コメント数:
- Comments: 0
◆ lit-html パッケージ内に polyfill が付属してた
◆ template タグの最低限の機能の polyfill
◆ WebComponents の polyfill なしでいい
◆ template タグの最低限の機能の polyfill
◆ WebComponents の polyfill なしでいい
lit-html に polyfill がついてた
lit-html では WebComponents の template 機能が必要なので polyfill が必要ですそれをいれると core-js との競合で問題が起きたり色々面倒で IE でもとりあえず表示したいようなページでは楽に使える hyperhtml のほうを使ってました
最近 なんとなく lit-html のフォルダを眺めていたら polyfills というフォルダがありました
これまで気づいてませんでしたが これを使えば面倒な polyfill 周りの問題が解決しそうな気がします
Github ではコンパイル前の TypeScript コードしかないですが 中身はこれです
https://github.com/Polymer/lit-html/blob/master/src/polyfills/template_polyfill.ts
/**
* A lightweight <template> polyfill that supports minimum features to cover
* lit-html use cases. It provides an alternate route in case <template> is not
* natively supported.
* Please note that nested template, cloning template node and innerHTML getter
* do NOT work with this polyfill.
* If it can not fulfill your requirement, please consider using the full
* polyfill: https://github.com/webcomponents/template
*/
説明を見た感じでは lit-html が使う機能を最低限カバーしてる <template> タグの軽量 polyfill だそうです
テンプレートのネストや クローンや innerHTML の getter は使えないようです
lit-html を使うなら template タグを独自に操作することなんて基本ないので十分です
重い上に分かりづらいエラーが起きる WebComponents の フル polyfill を入れなくて済むなら助かります
使ってみる
自動でロードしてくれればいいのに コードを見た感じでは内部的に import するコードはなくて 外部からロードして使う必要があるようです動くかどうか IE で試してみます
[index.html]
<script src="index.js"></script>
表示用の HTML です
index.js は webpack でバンドルした出力です
[src.js]
import "core-js/stable"
import "regenerator-runtime/runtime"
import { html, render } from "lit-html"
import { initTemplatePolyfill } from "lit-html/polyfills/template_polyfill.js"
initTemplatePolyfill()
const update = () => render(html`<h1>${Math.random()}</h1>`, document.body)
setInterval(update, 1000)
このファイルを webpack でバンドルします
使い方は initTemplatePolyfill を最初に呼び出すだけです
引数は force の 1 つだけで true を渡せば常に polyfill が使われます
基本は自動で必要か判断してくれるので常に呼び出して大丈夫です
[webpack.config.js]
module.exports = {
mode: "development",
entry: "./src.js",
output: {
path: __dirname,
filename: "index.js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /core-js/,
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
],
},
],
},
}
src.js をバンドルした結果を index.js に出力します
core-js は Babel で変換するとエラーになるので exclude してます
Babel を通すと IE で 「Incompatible receiver, Symbol required」 というエラーが出ました
https://github.com/zloirock/core-js/issues/514
あとは package.json などで browserslist に IE 11 を指定します
{
"browserslist": [
"IE 11"
]
}
webpack 後に IE で開いた結果 無事 lit-html が動きました
IE で動かす必要自体がなくなりつつありますが hyperhtml だけじゃなく lit-html でも簡単に動かせたので 選択肢が広がりました