DEV Community

hiro@
hiro@

Posted on

Daily Blog Vol.2

My issues about web components

I've been interested in using web components as my hobby project. also I've written about it at my self-publication book for 2 times. it made me gaining my knowledge of it though, I still have a question or problem about it.

Hot Module Replacement problem.

Have you tried to setup HMR for your project which is used web components? I've tried it, but it didn't work well for me. Honestly, I've not tried for SPA environment. it's just for static page or simple page, so it's not big problem for me. but what if you (of course it's included me) wanna use web components for project which is SPA environment? Can't use HMR for SPA environment should be crucial probably. at least I must be troublesome.

Why can't we use HMR on web components project?

Simply, if custom elements's registered, you can't revoke it. custom elements doesn't have a specification for revoking defined custom elements from customElementsRegister. This is the point, we can't use HMR. if it's possible, we can revoke defined custom elements, then redefine new custom elements. Let me describe about it as below.


import { html, render } from 'lit-html';

class SampleBtn extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: 'open' });
  }

  template() {
    // I assume to change "test!!!" to "this is it!" later for checking whether HMR works or not.
    return html`<div>test!!!</div>`;
  }

  render() {
    render(this.template(), this.shadow);
  }

  connectedCallback() {
    this.render();
  }
}
if (!window.customElements.get('SampleBtn')) {
  window.SampleBtn = SampleBtn;
  window.customElements.define('sample-btn', SampleBtn);
}

this is a entry point.

import './web-components/SampleBtn';

if (module.hot) {
  module.hot.accept('./web-components/SampleBtn.js', () => {
    // Somehow I wanted to enable HMR for web components,
    // fortunately, it did work for javascript, but custom elements didn't update itself.
    // here is empty now, but I tried many things.
    // However, Everything was failed.
  });
}

Internal of SampleBtn 's code which is such as console.log was invoked well, but if I changed inside of template() method, HMR didn't work well.
I'm kind of feeling, if HMR doesn't work well for project of web components which is SPA environment, it's inconvenient as I firstly mentioned.

I should gain knowledge of behind of how HMR works or custom elements or something like that though, I fatigued actually.
Well, this is my today's research of web components (custom elements) on HMR environment.

if you have a question or advice to me, feel free to reach out to me on here or twitter !

That's it! See you tomorrow!

Top comments (0)