javascript - 当托管在与应用程序本身不同的域上时,如何为 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.css和WebComponent.html。但是,它应该从与其托管位置相关的 URL 中获取 ( )。localhost
https://storage.googleapis.com/storage-bucket/
任何想法如何实现这样的目标?无需将 url 硬编码到两个 fetch 调用中。这不是一个选项,因为 url 会不时自动更改。
解决方案
您在 JS 网页中链接资源时遇到问题:
- 本地组件正在工作
- 从“./WebComponent”导入 WebComponent;
- 远程组件失败
- 从“URL”导入 WebComponent;
可能是为了让这个工作你应该试试这个:
<script type="module" src="https://storage.googleapis.com/storage-bucket/WebComponent.js">
customElements.define("web-component", WebComponent);
</script>
参考 :
推荐阅读
- python-3.x - 已安装模块:ModuleNotFoundError:没有名为“pygame”的模块
- javascript - ASP.NET Core 3.0:当 OnPost() 被命中时显示 GIF
- swift - 映射 EventLoopFuture 时出错
到预期的类型 - java - 设置高亮recyclerview元素被点击,但在开头全部高亮
- python - 如何使用scrapy提取两个不同字符之间的部分URL
- scala - Dotty 中多个参数列表的更好类型推断
- python - Django json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)
- python - GET api 请求在 POSTMAN 中有效,但在 python 代码中无效,我想将响应下载为 csv
- rest - Splunk 是否提供任何此类解决方案来调用 SOAP REST HTTP URL 并测试其可用性?
- sql-server - SQL Server Profiler:如何过滤会话上下文键的值?