Redefined a Web Component

02/05/2022, Sat
Categories: #JavaScript

HMR with Web Components

Say that you are using HMR in conjunction with web components for your layouts, you would expect a change in the component's JavaScript logic to trigger the HMR code to re-register the component.

However, there isn't a way to redefine a web component once it has already been defined and registered onto the page, an error will be thrown if you tried to redefine the web component again.

As of this writing on Feb 2022, there also isn't a method for web components for removal, such that the option to remove and redefine is not possible. (https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry)

Alternatively, it is possible to check for an existence of a web component, and once it is found to be already defined, one can force a refresh of the entire page instead.

if (!window.customElements.get('my-web-component')) {
  location.reload();
}

Through the basic APIs for interacting with web components, there isn't a way for web components to work with HMR, but there is a way to do "limited HMR" with web components if you use a specific implementation of "@open-wc/dev-server-hmr".