【问题标题】:Relative paths in custom component library自定义组件库中的相对路径
【发布时间】:2015-08-10 08:38:04
【问题描述】:

我的项目结构看起来像这样

-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。

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

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    你可以使用绝对网址吗?

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

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

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

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

    所以,总而言之,不要在模板内使用 css @import 硬编码样式标签,根据您当前导入的 html 的 url 构造它并将其注入到模板中。

    可能是这样的:

    //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 :)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2012-03-24
      • 2015-12-28
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多