Javascript 使用单独的html和js文件创建普通js web组件
在创建vanilla JS web组件时,我试图找到一种方法将模板html保存在JS文件之外,最好是保存在单独的html文件中 我确实研究了本地JS web组件实现的多个实现,尤其是 所有的实现最终都使用字符串文本或类似的方法将html模板放在JS中。我的问题是,是否有可能创建两个单独的文件,例如模板的Javascript 使用单独的html和js文件创建普通js web组件,javascript,html,web-component,native-web-component,Javascript,Html,Web Component,Native Web Component,在创建vanilla JS web组件时,我试图找到一种方法将模板html保存在JS文件之外,最好是保存在单独的html文件中 我确实研究了本地JS web组件实现的多个实现,尤其是 所有的实现最终都使用字符串文本或类似的方法将html模板放在JS中。我的问题是,是否有可能创建两个单独的文件,例如模板的My component.html,js代码的My component.js 我已经看到这种方法在Aurelia框架中很好地工作,它非常干净,并将代码保持在它所属的位置 我尝试使用html导入,为
My component.html
,js代码的My component.js
我已经看到这种方法在Aurelia框架中很好地工作,它非常干净,并将代码保持在它所属的位置
我尝试使用html导入,为模板创建一个html文件,并在其中包含js
<link rel="import" href="my-component.html">
从服务器端,我只返回纯html
// my-component.html
<style>
@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import 'https://code.getmdl.io/1.3.0/material.${this.theme}.min.css';
@import 'http://fonts.googleapis.com/css?family=Roboto:300,400,500,700';
@import 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'
}
table {
border-collapse: collapse;
}
td {
text-align: center;
border: 1px solid #f7f7f7;
padding: 1rem;
}
th {
background-color: #f7f7f7;
text-align: center;
padding: 1em;
border: 1px solid #e9e9e9;
}
</style>
<div class="search-list table-responsive">
<table width="100%" class="table table-bordered table-striped table-hover">
<thead class="thead-light">
<tr>
<th width="1rem">
<input type="checkbox">
</th>
<th>
ID
</th>
<th>
name
</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>
1
</td>
<td>
some name
</td>
</tr>
</tbody>
</table>
</div>
//my-component.html
@进口的https://fonts.googleapis.com/icon?family=Material+图标';
@进口的https://code.getmdl.io/1.3.0/material.${this.theme}.min.css';
@进口的http://fonts.googleapis.com/css?family=Roboto:300,400,500,700';
@进口的https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'
}
桌子{
边界塌陷:塌陷;
}
运输署{
文本对齐:居中;
边框:1px实心#f7f7f7;
填充:1rem;
}
th{
背景色:#f7f7f7;
文本对齐:居中;
填充:1em;
边框:1px实心#e9e9e9;
}
身份证件
名称
1.
某个名字
请注意,我是如何在来自服务器的响应中跳过了
标记的,很明显,如果我使用
标记,我将不得不使用dom解析来实际将html放入dom中
这确实管用,但看起来太粗糙了
有人有更好的方法吗?您的解决方案很好,但您可以插入Javascript代码:
class MyComponent extends HTMLElement {
async connectedCallback() {
let res = await fetch( 'my-component.html' )
this.attachShadow( { mode: 'open' } )
.innerHTML = await res.text()
}
}
customElements.define( 'my-component', MyComponent )
下面是我编写的一个工具,它使用Rollup将HTML和语言环境文件转换为代码可以导入的内容,然后将其打包为每个组件的单个文件:我写了一篇中等规模的文章,其中有一个可能的解决方案
class MyComponent extends HTMLElement {
async connectedCallback() {
let res = await fetch( 'my-component.html' )
this.attachShadow( { mode: 'open' } )
.innerHTML = await res.text()
}
}
customElements.define( 'my-component', MyComponent )