使用 Web 组件的 Vanilla hello world 应用程序
Vanilla hello world app using web components
我正在尝试构建一个没有任何外部依赖项的简单 Web 组件。只有两个 html 个文件,一个 index.html 和一个 webcomponent.html.
我有一些个人 html 项目,我想在其中将全局 html 命名空间分离成较小的文件。我不想为此使用任何外部库,如聚合物。我也不想使用任何构建系统或网络服务器。
我在网上找到的所有示例都需要外部构建系统或库。此外,如果没有网络服务器,它们也不会工作。例如,webcomponents/hello-world 声称使用 vanilla-js。但实际上并没有,因为它依赖于Bower。
只有两个 html 文件可以在我的本地编辑-保存-刷新开发周期中使用。这真的可能吗?如果是这样,如何?如果不是,最接近的折衷方案是什么?
这是一个包含 2 个文件的最小自定义元素示例:
1. 在单独的文件中创建自定义元素,例如 hello-world.js:
class HelloWorld extends HTMLElement {
connectedCallback () {
this.innerHTML = 'hello, world!'
}
}
customElements.define( 'hello-world', HelloWorld )
2. 在主文件中导入并使用您的自定义元素,index.html 文件:
<html>
<head>
<script src='hello-world.js'></script>
<body>
<hello-world></hello-world>
代码:
class HelloWorld extends HTMLElement {
constructor() {
super();
// Attach a shadow root to the element.
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `<p>hello world</p>`;
}
}
customElements.define('hello-world', HelloWorld);
<hello-world></hello-world>
我正在尝试构建一个没有任何外部依赖项的简单 Web 组件。只有两个 html 个文件,一个 index.html 和一个 webcomponent.html.
我有一些个人 html 项目,我想在其中将全局 html 命名空间分离成较小的文件。我不想为此使用任何外部库,如聚合物。我也不想使用任何构建系统或网络服务器。
我在网上找到的所有示例都需要外部构建系统或库。此外,如果没有网络服务器,它们也不会工作。例如,webcomponents/hello-world 声称使用 vanilla-js。但实际上并没有,因为它依赖于Bower。
只有两个 html 文件可以在我的本地编辑-保存-刷新开发周期中使用。这真的可能吗?如果是这样,如何?如果不是,最接近的折衷方案是什么?
这是一个包含 2 个文件的最小自定义元素示例:
1. 在单独的文件中创建自定义元素,例如 hello-world.js:
class HelloWorld extends HTMLElement {
connectedCallback () {
this.innerHTML = 'hello, world!'
}
}
customElements.define( 'hello-world', HelloWorld )
2. 在主文件中导入并使用您的自定义元素,index.html 文件:
<html>
<head>
<script src='hello-world.js'></script>
<body>
<hello-world></hello-world>
代码:
class HelloWorld extends HTMLElement {
constructor() {
super();
// Attach a shadow root to the element.
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `<p>hello world</p>`;
}
}
customElements.define('hello-world', HelloWorld);
<hello-world></hello-world>