How can I turn off ViteJS's Hot Module Reload?
Asked Answered
S

3

15

I have a server side rendered production mode Vite application. My issue is that: routinely the webpage will reload and the console will display [vite] connecting.... I traced this back to the hot module reload portion of vite's codebase. However, I do not want hmr on for production, but it still seems to be on regardless of me setting the two settings below to false:

In my vite.config.js file I have:

...
export default defineConfig({
  server: {
    hmr: false,
  },

Also in my NodeJS server.js file I have:

const vite = await createViteServer({
  server: { middlewareMode: 'ssr', hmr: false },
})

How can I turn off Vite's hmr?

Smog answered 8/6, 2022 at 15:57 Comment(1)
server: { hmr: { overlay: false } }Oops
Z
5

Just modify the server property in vite.config.ts:

server: {
    hmr: false
}

(This seems to be the simplest way.)

Credit: https://mcmap.net/q/825910/-disable-auto-reload-vite-reactjs

Zoarah answered 22/4 at 15:0 Comment(0)
B
2

Add this to your app.js file:

if (import.meta.hot)
import.meta.hot.accept(() => import.meta.hot.invalidate())

and in your vite.config.js file add false to 'defineConfig':

// server.hmr.overlay property
defineConfig({          
    server: {
        /*here*/
        hmr: { overlay: false }
    }, ...
  })
Bowel answered 15/12, 2022 at 21:10 Comment(1)
It's important to not just post the question, but to also include a description of what the code or question does and why you are suggesting or asking it. This helps others understand the context and purpose of the question, and makes it more useful for others who may be reading the question. @Deubledee.Lucic
U
1

Vite has a HMR API that allows you to invalidate modules during a reload. You might also be interested in HMR Server Config which can be configured in your vite.config.ts file.

// index.ts
if (import.meta.hot) {
    import.meta.hot.accept(() => {
        import.meta.hot.invalidate();
    })
}

Vite also had a --no-hmr flag for disabling hot module reloads.

vite --no-hmr

Unfortunately, both these solutions didn't work for me. Which is why I added the following code to my main/index file for forcing the browser to reload after HMR took place.

// index.ts
if (window['reload']) window.location = window.location;
window['reload'] = true;

Alternatively, you can add the following plugin to your vite.config.ts if you wish to full reload instead of hot module reload.

{
    name: 'full-reload',
    handleHotUpdate({ server }) {
        server.ws.send({ type: "full-reload" })
        return [];
    }
}
Unwisdom answered 18/9, 2023 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.