How to solve "Uncaught TypeError: Illegal constructor"

This is a quite common error, frequently appearing for people building or using Custom Elements and Web Components.

Let's take this class as an example:

export default class LoadingIndicator extends HTMLElement {
  constructor() {
    super();
  }
}

new LoadingIndicator(); // Uncaught TypeError: Illegal constructor

The Illegal constructor error is thrown when a class extends HTMLElement, but is instantiated like a regular class.

Using classes that inherits from HTMLElement requires you to define them as custom elements to initialize them, like this:

customElements.define("loading-indicator", LoadingIndicator);

Then you use it as a custom element:

<loading-indicator></loading-indicator>