Search code examples
reactjsvitewebpack-hmrsolid-js

Detect HMR event with ViteJS React/SolidJS


Using ViteJS starter for React / SolidJS,

How can I detect (using some sort of js callback) before HMR reload is triggered by code changes? (to do some cleanup)

To be clear, I'm not asking how to use HMR, just how to do some cleanup before that happens.

I have tried using window.onbeforeunload to no avail.

Thanks.


Solution

  • window.onbeforeunload does not work because in HMR the page is never reloaded. The way HMR works is by patching the existing modules with new ones received via websocket.

    You can hook into update pipeline using the HMR API. https://vitejs.dev/guide/api-hmr.html#hot-accept-cb

    You can use accept method inside your module accepting the patch:

    if (import.meta.hot) {
      import.meta.hot.accept((newModule) => {
        console.log(`Receving new module...`, newModule);
      });
    }
    

    Or you can add an event listener in your main file:

    if (import.meta.hot) {
      import.meta.hot.on('vite:beforeUpdate', () => {
        console.log('Running before update!!');
      });
    }
    

    Alternatively you can watch network events using a service worker. Create a JavaScript file with the content watching fetch events:

    // sw.js
    self.addEventListener('fetch', function(event) {
      console.log(event);
    });
    

    And register the service worker in your main file:

    navigator.serviceWorker.register('/sw.js');