是否可以使用 ES2015 导入模板标签? [英] Is is possible import template tag with ES2015?

查看:25
本文介绍了是否可以使用 ES2015 导入模板标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读,但我没有找到任何内容,是否可以在不同的 html 文件中定义并使用 ESModule 导入以与 shadowRoot 一起使用,可能是吗?

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

<html lang="zh-cn"><头><meta charset="utf-8"><title>我的第一个组件</title><meta name="description" content="我的第一个组件"><meta name="author" content="Ismael Rodriguez"><script type="module" src="js/my-template.js"></script><script type="module" src="js/component.js"></script><!--<模板 id="我的模板"><h2>你好世界</h2>--><身体><h1>网络组件</h1><hello-world></hello-world>

js/my-template.js,在这个模块中只导出一个带有标签html的字符串.

export const 模板 = `<风格>h3{红色;字体系列:helvetica;}</风格><h3>你好世界</h3>`;

js/component.js,最后导入模块my-template.js.我发现这种方法可以使用 ESmodule 从我的模块中解释模板.我如何导入模板并在我的组件中使用(支持 Firefox)?

import {template} from './my-template.js';class HelloWorld 扩展 HTMLElement{构造函数(){极好的();让 shadowRoot = this.attachShadow({mode: 'open'})const t = this.createTemplate(模板);const 实例 = t.content.cloneNode(true);shadowRoot.appendChild(instance);/*console.log(模板);const t = document.querySelector('#my-template');const 实例 = t.content.cloneNode(true);shadowRoot.appendChild(instance);*/}创建模板(html){const template = document.createElement('template');html = html.trim();模板.innerHTML = html;返回模板;}}window.customElements.define('hello-world',HelloWorld);

解决方案

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

如果您想导入一个元素,您需要将它放在一个 Javascript 文件中,例如使用模板文字字符串.

template.js:

export var template = `