Paths in Web Components are Relative to Root

前端 未结 3 1957
余生分开走
余生分开走 2020-12-29 09:16

I am creating a web component using native implementation, which in it\'s html template has links to images. However, those links only work if they are absolute, or relative

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 09:41

    Reacting on my own prev comment to MarcG answer - the need for the modules to be aware of their own path has become acknowledged and nowadays may be retrieved by the import.meta.url mean!

    So it is much easier to write now some util to fetch component's HTML/CSS.

    Furthermore, if CSS is NOT fetched, but a new style sheet link dynamically added to the document - this CSS plays very well with relative paths furthermore.

    Having that, today, while waiting for some standard way to specify my component's base url, my ow approach is to provide a component with 2 resources:

    • main/single HTML is fetched via fetch API, turned into template, cached and then cloned into the component each time new instance of it attached to the DOM
    • main CSS is linked by the standard link element
    • names of those 2 are the same as the main JS file providing component's class - making it easier to turn this whole mess into a dozen-of-lines-util
    • additional CSS resources, if needed, added as a regular relative imports in the main CSS
    • images, if possible, added as url backgrounds using relative imports as well
    • no more than singe HTML resource obviously

提交回复
热议问题