使用 Web 组件的 Vanilla hello world 应用程序

Ruu*_*jah 5 html javascript web-component custom-element

我正在尝试构建一个没有任何外部依赖项的简单 Web 组件。只有两个 html 文件,一个 index.html 和一个 webcomponent.html。

我有一些个人 html 项目,我想将全局 html 命名空间分成更小的文件。我不想为此使用任何像聚合物这样的外部库。我不想使用任何构建系统或网络服务器。

我在网上找到的所有示例都需要外部构建系统或库。此外,如果没有网络服务器,它们也不会工作。例如,webcomponents/hello-world声称使用 vanilla-js。但事实上,它不是,因为它取决于鲍尔。

只有两个 html 文件在我的本地编辑-保存-刷新开发周期中工作。这真的可能吗?如果是这样,如何?如果没有,最接近的妥协是什么?

Sup*_*arp 7

这是一个包含 2 个文件的最小自定义元素示例:

1.在单独的文件中创建您的自定义元素,例如hello-world.js

class HelloWorld extends HTMLElement {
    connectedCallback () {
        this.innerHTML = 'hello, world!'
    }
}
customElements.define( 'hello-world', HelloWorld )
Run Code Online (Sandbox Code Playgroud)

2.在主index.html文件中导入并使用您的自定义元素:

<html>
<head>
    <script src='hello-world.js'></script>
<body>
    <hello-world></hello-world>
Run Code Online (Sandbox Code Playgroud)

  • 不再支持 HTML 导入,并且可能永远不会支持:/sf/ask/2408621631/ (2认同)