13

Html-Imports は Chrome ( https://www.chromestatus.com/feature/5144752345317376 ) で非推奨になり、削除されるため、代替手段は何だろうか。

現在、Html-Imports を使用して Html-Templates をインポートしています。これまでのところ、2 つの選択肢しかありません。

  • すべての HTML ファイルを 1 つのファイルにまとめる。これにより、本番環境でのダウンロード時間も短縮されますが、カプセル化とモジュール化が減少します。分離された HTML ファイル内の HTML インポート ステートメントをトラバースすることによってジョブを実行するポリマー バンドラーがあります。ただし、これは、将来的にブラウザーでサポートされなくなったとしても、HTML インポートがコードに残ることを意味します。
  • XHttpRequests を使用してある種のモジュール ローダーを構築し、実行時にテンプレートを 1 つの HTML ファイルに編成します。これにより、カプセル化とモジュール化が維持されますが、基本的に自分で import-Statements を再構築するので、これは私には悪臭を放ちます。

Html テンプレートをインポートする新しいバニラの方法はありますか? (「バニラ」とは、基本的に、プリコンパイラやバンドラーなどの追加ツールを使用しない方法を意味します)

4

2 に答える 2

1

index.html:

<script type="module">
  import { CustomHTMLElement } from './CustomHTMLElement.js'

  customElements.define('custom-html-element', CustomHTMLElement)
</script>

<custom-html-element></custom-html-element>

CustomHTMLElement.js:

import { createTemplate } from './createTemplate.js'

const template = createTemplate(`
  <template>
    <style>
      .box {
        width: 2rem;
        height: 2rem;
        background-color: red;
      }  
    </style>
    <div class="box"></div>
  </template>
`)

export class CustomHTMLElement extends HTMLElement {
  constructor() {
    super()
    const templateContent = template.content
    const shadowRoot = this.attachShadow({mode: 'closed'})
    shadowRoot.appendChild(templateContent.cloneNode(true))
  }
}

createTemplate.js:

import { createDOM } from './createDOM.js'

export function createTemplate(templateText) {
  const dom = createDOM(templateText)
  const template = dom.querySelector('template')
  return template
}

createDOM.js:

export function createDOM(htmlText) {
  return new DOMParser().parseFromString(htmlText, 'text/html')
}

Unlicense ライセンスでライセンスされているコードについては、https://github.com/SanjoSolutions/web-componentsを参照してください。

于 2021-01-30T14:04:33.810 に答える