Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 856
Alon Amir Avatar asked Nov 01 '25 11:11

Alon Amir


1 Answers

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');
like image 108
snnsnn Avatar answered Nov 04 '25 14:11

snnsnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!