我正在寻找一个干净的解决方案,将web组件拆分为JS、HTML和CSS文件,并将它们保存在CDN上。我试图避免webpack html和css-加载程序,因为他们不允许我导出我的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 */
}WebComponent.html:
<button>Custom buttom</button>我可以通过使用浏览器本机ES模块导入组件:
index.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不同的位置(谷歌云存储桶),并从那里导入index.html,这才能奏效。
<!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的localhost的URL中获取WebComponent.css和WebComponent.html。但是,它应该从相对于托管位置(https://storage.googleapis.com/storage-bucket/)的URL中获取。
有什么办法可以实现这样的事情吗?无需将url硬编码到两个提取调用中。这不是一个选项,因为url可以不时自动更改。
发布于 2021-10-08 16:49:44
您对JS网页中的资源链接存在问题,其中:
"./WebComponent";
"URL";
也许要想让它起作用,您应该尝试以下几种方法:
<script type="module" src="https://storage.googleapis.com/storage-bucket/WebComponent.js">
customElements.define("web-component", WebComponent);
</script>参考资料:
发布于 2021-10-11 17:39:02
JavaScript文件路径相对于显示的页面。所以你所观察到的行为是预料之中的。
您可以在下面的简单js声明中使用JavaScript变量,并且每当动态分配URL时都可以使用该变量:
<script type="text/javascript">
var webComponentPath = 'https://storage.googleapis.com/storage-bucket/';
</script>https://stackoverflow.com/questions/69413201
复制相似问题