Search code examples
javascripttypescriptweb-component

Can not render web component


I can not render my web component. I created a class HelloWC.ts which has the only one task (render Hello inside <h2> tag). I used tsconfig.json to define how to build /dist directory which contain HelloWC class translated to es6. In index.html file, I added <script> tag (in the end of the <body>) in which I imported my HelloWC component from /dist directory. Then I wanted to render my <hello-wc> component inside index.html <body> tag. If I inspect my index.html served by server-http I can see that there is a <hello-wc></hello-wc> tag but it is empty. In the network card I can also see that HelloWC.js was download successfully. I also added a simple console.log() to the constructor of my component but the message is never logged (it looks like my component is never created). I have no idea why my component can not render properly. If you have any idea let me know.

HelloWC.ts

const template: string = `<div>
    <h2>Hello</h2>
</div>`;

export class HelloWC extends HTMLElement {
    shadowRoot!: ShadowRoot;

    public static TAG = 'hello-wc';

    constructor() {
        super();
        console.log('heelo wc');
        this.attachShadow({ mode: 'open'});
        this.shadowRoot.innerHTML = template;

    }
}
customElements.define(HelloWC.TAG, HelloWC);

index.html

<!DOCTYPE html>
<html lang="pl">
    <head>
        <meta charset="UTF-8">
        <title>Hello WC</title>
    </head>
    <body>
        <hello-wc></hello-wc>
        <script src="/dist/HelloWC.js" type="module"></script>
    </body>
</html>

tsconfig.json

{
  "compilerOptions": {
    "module": "umd",
    "target": "es6",
    "sourceMap": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "removeComments": true,
    "moduleResolution": "node"
  },
  "exclude": [
    "src",
    "node_modules",
    "dist"
  ]
}

Project structure

enter image description here


Solution

  • It seems that you are importing the compiled file as ES module, however, tsconfig.json you have specified "module": "umd" (it should be es6 or esnext not umd if you want the ES modules)