Is it possible to cleanup in a node.js module, before Vite is page reloading on file change?

Viewed 586

I'm developing a node.js application, using Sveltekit + vite.

I have a file, where I attach event-listeners.

When I change the specific file, a new listener is attached but the old one is still active.

Is it possible somehow to hook into the Vite page reload life-cycle?

I currently tried to listen for proceess.on('SIGINT|'SIGTERM'|'SIGHUP'), but that did not help.

1 Answers

To achieve that you can write a plugin to hook on handleHotUpdate.

Look at the following small plugin example :

custom-hot.ts :

/**
 * Custom Hot Reloading Plugin
 */

const data = 1337

export default function CustomHot() {
    return {
        name: 'custom-hot',
        enforce: 'post',
        handleHotUpdate({ file, server }) {

            console.log('> custom hot update', 'HotUpdate Hook')
            
            server.ws.send({
                type: 'custom',
                event: 'custom-hot',
                data: {"dummyData": data}
            })

            console.log('> Look at websockets messages for the event then look at your developer console to see the message from `hmr.ts`...', 'HotUpdate Hook')
        }
    

vite.config.ts:

[...]

plugins: [
  customHot()
],

[...]

hmr.ts

/**
 * Customized HMR module
 * eg: could be used to keep safe stores values with svelte/store
 */ 
 
if (import.meta && import.meta.hot) {
  import.meta.hot.accept()
  import.meta.hot.on('custom-hot', (data) => {
      console.log('received event with data: ' , data)
  })  
} 

Now to see the result, save the module file hmr.ts and then :

  • a custom event with custom data is fired through websockets:

enter image description here

  • once received, you can see a message log on the developer tool:

enter image description here

For more information, head to the offical doc at

Related