首页 > 解决方案 > 在 TypeScript 和 HTML 中定义、导入和使用自定义元素

问题描述

我正在尝试定义一个自定义元素并在 HTML 模板中使用它,但它没有显示,控制台没有记录任何内容。似乎元素没有以这种方式定义。

我究竟做错了什么?我正在使用 webpack 和 TypeScript。

我在 top-bar.ts 中定义了一个扩展 HTML 元素的类

export class TopBar extends HTMLElement {

    shadowDOM : ShadowRoot;

    constructor() {
        super();
        console.log('from constructor');
        this.shadowDOM = this.attachShadow({mode:"open"});
    }

    connectedCallback() : void {
        this.render();
    }

    render() : void {
        this.innerHTML = `

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <style>
            .top-bar {
                box-shadow: 0px 2px 10px 6px #ccc;
                height: 40px;
            }
            
            .top-bar h5 {
                margin-bottom: 0;
                color: #273C75;
            }
            
            .top-bar img {
                display: block;
                width: 36px;
                height: 36px;
                margin-right: 0.5rem;
            }
        </style>
        <nav class="top-bar d-flex justify-content-center align-items-center">
            <img src="img/Beep-Signal.png" alt="">
            <h5>LoRa Dashboard</h5>
        </nav>
        `
    }

}

customElements.define("top-bar", TopBar);

在 index.ts 中,我导入了 TopBar。

import * as TopBar from './components/top-bar'

在 index.html 中,我放置了 top-bar 元素

<!DOCTYPE html>
<html>
  <head>
    <title>LoRa Dashboard</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  </head>
  <body>
    <script src="bundle.js"></script>
    <top-bar></top-bar>
  </body>
</html>

标签: typescriptcustom-element

解决方案


所以过了一会儿,我终于发现 top-bar.ts 似乎没有包含在包中。

尽管我已在 index.ts 中导入了 top-bar,但似乎没有包含 top-bar,我的怀疑是因为在 index.ts 中的任何地方都没有使用 top-bar.ts 中的任何内容,仅在 HTML 中(测试时)。这就是为什么自定义元素永远不会被定义的原因。

所以我在 top-bar.ts 中添加了一个虚拟函数,并在 index.ts 中调用它只是为了将其包含在内。这目前适用于我的项目,而且我是 TypeScript 和 JavaScript 的新手,但我确信有更好的解决方法,而不是仅仅为了包含它而调用一个虚拟函数。


推荐阅读