ES2015是否可以导入模板标签?

时间:2018-10-30 11:39:31

标签: web-component

我一直在阅读,但是我找不到任何东西,是否可以在其他html文件中定义并导入ESModule以与shadowRoot一起使用?

index.html ,在其中定义2个javscript模块并使用组件<hello-world></hello-world>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>My First Component</title>
    <meta name="description" content="My First Component">
    <meta name="author" content="Ismael Rodriguez">
    <script type="module" src="js/my-template.js"></script>
    <script type="module" src="js/component.js"></script>
    <!--
        <template id="my-template">
            <h2>Hello World</h2>
         </template>
    -->
</head>

<body>
    <h1>Web Component</h1>
    <hello-world></hello-world>
</body>

js / my-template.js ,在此模块中,仅导出带有标签html的字符串。

export const template = `
    <style>
        h3 {
            color: red;
            font-family: helvetica;
        }
    </style>
    <h3>Hello World</h3>
`;

js / component.js ,最后导入模块my-template.js。我已经找到了使用ESmodule从我的模块解释模板的方法。如何导入模板并在组件中使用(带有Firefox支持)?

import {template} from './my-template.js';

class HelloWorld extends HTMLElement{

    constructor(){
        super();
        let shadowRoot = this.attachShadow({mode: 'open'})
        const t = this.createTemplate(template);
        const instance = t.content.cloneNode(true);
        shadowRoot.appendChild(instance);

        /*console.log(template);
        const t = document.querySelector('#my-template');
        const instance = t.content.cloneNode(true);
        shadowRoot.appendChild(instance);*/

    }

    createTemplate(html){
        const template = document.createElement('template');
        html = html.trim();
        template.innerHTML = html;
        return template;
    }
}

window.customElements.define('hello-world',HelloWorld);

2 个答案:

答案 0 :(得分:2)

您只能将Javascript文件作为ES6模块导入。

如果要导入元素,则需要将其放入Javascript文件,例如,使用模板文字字符串。

template.js

export var template = `<template>
    <h1>Content title</h1>
    <div>Content</div>
  </template>`

但这没有意义。相反,您可以直接定义内容模板。

templates.js

export var literal1= `
    <h1>Content title</h1>
    <div>Content</div>
  `

index.html

<div id=host></div>
<script type="module">
    import * as templates from './templates.js'
    host.attachShadow( {mode:'open'} )
        .innerHTML = templates.literal1
</script>

或者,如果要将DOM元素保留在HTML文件中,则可以使用fetch()导入文件,如this post about HTML Imports中的代码所示。

答案 1 :(得分:1)

我同意@Supersharp,没有真正的理由使用template对象,因为您可以只设置影子DOM的innerHTML

以@Supersharp的示例为更进一步,这里是您的代码经过改进:

import {template} from './my-template.js';

class HelloWorld extends HTMLElement{

    constructor(){
        super();
        this.attachShadow({mode: 'open'}).innnerHTML = template'
    }
}

window.customElements.define('hello-world',HelloWorld);

相关问题