javascript - 自定义组件库中的相对路径

标签 javascript css relative-path custom-component shadow-dom

我的元素结构如下所示

-client
----index.html
----index.ts
-core
----controls
--------myControl.html
--------myControl.ts
----css
--------common.css

myControl.html 包含通过 shadow dom 注册的自定义组件的定义。 在其模板中导入作为“核心”库一部分的 common.css:

<template id="t">
    <style>
        @import url('../css/common.css');
    ....
    </style>
    ....
</template>
<script>
  (function() {
      var importDoc = document.currentScript.ownerDocument; // importee

      var proto = Object.create(HTMLElement.prototype);

      proto.createdCallback = function() 
      {
          // get template in import
          var template = importDoc.querySelector('#t');

          // import template into
          var clone = document.importNode(template.content, true);

          var root = this.createShadowRoot();
          root.appendChild(clone);

          var control = this;

          System.import('core/controls/myControl').then(function(m)
          {
              var t = new m.myControl(control.shadowRoot);
          });
      };

      document.registerElement('my-control', {prototype: proto});
  })();
</script>

现在,当我在 index.html 上使用 my-control 时,浏览器会提示它无法导入 common.css。因为它使用相对于 index.html 的路径搜索它,而不是相对于其原始位置。我知道这是合乎逻辑的,因为我们已经从在 index.html 上下文中运行的脚本创建了 shadow dom。

我的问题是:我应该如何开发 my-control 自定义组件,它是“核心”库的一部分,可以在不同的地方重复使用/分发,并且仍然正确地引用资源,如 css/images/etc,它们也是“核心”库。

提前致谢。

最佳答案

可以使用绝对 URL 吗?

与您一样发布/deep/弃用,css @injects 是我们一直在组件中应用通用样式的方式。

但是如何识别共同风格的路径呢?

首先给出一些上下文,我们将我们的组件托管在一个单一的硫化 html 文件中,客户使用 html 导入在他们的应用程序中使用它。 现在,在这个 imports.html 中,我们包含了一个小脚本,它使用 document.currentScript.ownerDocument.baseURI 标识自己的 URL,并且由于我们知道 imports.html 的公共(public) css 相关路径,我们构造这个url 并在模板中注入(inject)包含 css @imports 的构造样式标签。

这样,当组件更新时(当 shadow-root 附加到它时)它会调用下载 common.css(因为它知道绝对 url)并在 shadow dom 中使用它.

因此,总而言之,不要在模板中使用 css @import 对样式标签进行硬编码,根据您当前导入的 html 的 url 构造它,并将其注入(inject)到模板中。

也许是这样的:

//URL of your html import or script being executed.
var host = document.currentScript.ownerDocument.baseURI;
//splice and dice your host url to get protocol and base url
...
// let's say it is proto and base
var cssURL = proto + base + '/core/css/common.css'
// construct a style tag here with css imports.
// Since you have access to document-fragment coming with html import
// find template and inject this style tag inside it.
// Remember to inject it at top :)

关于javascript - 自定义组件库中的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31915096/

相关文章:

javascript - 使具有圆边响应的 svg 路径

javascript - object 不是 menuitem 中的函数

javascript - 什么时候用 null 或根本不初始化 JavaScript 中的变量?

javascript - 如何让球击中桨时移动得更快?

html - 图片旁边的通讯文本模板代码 - 与某些电子邮件客户端的兼容性问题

jquery - Chrome "Find"中断滚动条

javascript - Heroku Nodejs 路径问题...错误 : ENOENT: no such file or directory

javascript - 使用带有数字 ID 的 querySelector

java - 使用 FileInputStream 从相对路径读取文件

css - 如何从 style.css 链接到 WordPress 插件文件夹?