首页 > 解决方案 > 当托管在与应用程序本身不同的域上时,如何为 Web 组件获取 HTML 和 CSS 文件?

问题描述

我正在寻找一种干净的解决方案,将 Web 组件拆分为 JS、HTML 和 CSS 文件并将它们托管在 CDN 上。我尽量避免使用 webpack html 和 css-loader,因为它们不允许我将 Web 组件导出为纯 ES 模块。

目标是使用任何前端应用程序中的 Web 组件,只需从指定的 URL 导入它即可。因此,应保留关注点的分离。样式、标记和逻辑的单个文件也允许语法突出显示。

在本地开发环境中,我发现以下内容效果很好:

WebComponent.js:

export default class WebComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });

    const style = new CSSStyleSheet();
    const template = document.createElement("template");

    fetch("./WebComponent.css").then((res) =>
      res.text().then((css) => {
        style.replaceSync(css);
        this.shadowRoot.adoptedStyleSheets = [style];
      })
    );

    fetch("./WebComponent.html").then((res) =>
      res.text().then((html) => {
        template.innerHTML = html;
        this.shadowRoot.appendChild(template.content.cloneNode(true));
      })
    );
  }
}

WebComponent.css:

button {
    /* Some styling */
}

网页组件.html:

<button>Custom buttom</button>

我可以使用浏览器原生 ES 模块导入来导入组件:

索引.html:

<!DOCTYPE html>
<html>
  <body>
    <web-component></web-component>

    <script type="module">
      import WebComponent from "./WebComponent";
      customElements.define("web-component", WebComponent);
    </script>
  </body>
</html>

这一直有效,直到我将 Web 组件文件移动到与index.html不同的位置(谷歌云存储桶)并从那里导入WebComponent.js 。

<!DOCTYPE html>
<html>
  <body>
    <web-component></web-component>

    <script type="module">
      import WebComponent from "https://storage.googleapis.com/storage-bucket/WebComponent.js";
      customElements.define("web-component", WebComponent);
    </script>
  </body>
</html>

WebComponent.js被正确导入,但它随后尝试从相对于 index.html 提供位置的URL获取WebComponent.cssWebComponent.html。但是,它应该从与其托管位置相关的 URL 中获取 ( )。localhosthttps://storage.googleapis.com/storage-bucket/

任何想法如何实现这样的目标?无需将 url 硬编码到两个 fetch 调用中。这不是一个选项,因为 url 会不时自动更改。

标签: javascriptgoogle-cloud-storagefetch-apies6-modulesnative-web-component

解决方案


您在 JS 网页中链接资源时遇到问题:

  • 本地组件正在工作
    • 从“./WebComponent”导入 WebComponent;
  • 远程组件失败
    • 从“URL”导入 WebComponent;

可能是为了让这个工作你应该试试这个:

<script type="module" src="https://storage.googleapis.com/storage-bucket/WebComponent.js">
      customElements.define("web-component", WebComponent);
</script>

参考 :


推荐阅读