[英]Vanilla hello world app using web components
I'm trying to build a simple web component without any external dependencies.我正在尝试构建一个没有任何外部依赖项的简单 Web 组件。 Just two html files, one index.html and one webcomponent.html.
只有两个 html 文件,一个 index.html 和一个 webcomponent.html。
I have some personal html projects where I'd like to separate out the global html namespace into smaller files.我有一些个人 html 项目,我想将全局 html 命名空间分成更小的文件。 I do not want ot use any external library like polymer for this.
我不想为此使用任何像聚合物这样的外部库。 Neither I want to use any build system or webserver.
我不想使用任何构建系统或网络服务器。
All the examples I found online either need an external build system or a library.我在网上找到的所有示例都需要外部构建系统或库。 Also they don't tend to work without a webserver.
此外,如果没有网络服务器,它们也不会工作。 For instance, webcomponents/hello-world claims to use vanilla-js.
例如, webcomponents/hello-world声称使用 vanilla-js。 But in fact, it does not as it depends on Bower.
但事实上,它不是,因为它取决于鲍尔。
Just two html files which work in my local edit-save-refresh development cycle.只有两个 html 文件在我的本地编辑-保存-刷新开发周期中工作。 Is this actually possible?
这真的可能吗? If so, how?
如果是这样,如何? If not, what's the closest compromise possible?
如果没有,最接近的妥协是什么?
Here is a minimal Custom Element example with 2 files:这是一个包含 2 个文件的最小自定义元素示例:
1. Create your custom elemnt in a separate file, for example hello-world.js : 1.在单独的文件中创建您的自定义元素,例如hello-world.js :
class HelloWorld extends HTMLElement {
connectedCallback () {
this.innerHTML = 'hello, world!'
}
}
customElements.define( 'hello-world', HelloWorld )
2. Import and use your custom element in the main, index.html file: 2.在主index.html文件中导入并使用您的自定义元素:
<html>
<head>
<script src='hello-world.js'></script>
<body>
<hello-world></hello-world>
Code:代码:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.