How do I enable full page reload on Ctrl+S?
Asked Answered
L

2

5

If im running vite dev server with "npm run dev" and I edit say utils.js, how do I make vite do a FULL reload from index.html so ALL the scripts gets reloaded?

The problem I have is: if I edit any files (and save, ctrl+s) except for index.html the vite server will reload once BUT my index.js will invoke twice? is this a vite.js bug?

Leede answered 6/2, 2022 at 15:50 Comment(0)
C
14

You have to configure a custom handleHotUpdate hook in vite.config.ts or vite.config.js (TypeScript/JavaScript)

handleHotUpdate documentation

The code below is adapted from an answer to this issue on GitHub: Option to force full reload on change, disabling HMR.

vite.config.ts:

import { defineConfig, PluginOption } from 'vite'
import react from '@vitejs/plugin-react'

const fullReloadAlways: PluginOption = {
  name: 'full-reload-always',
  handleHotUpdate({ server }) {
    server.ws.send({ type: "full-reload" })
    return []
  },
} as PluginOption

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), fullReloadAlways],
})

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

const fullReloadAlways = {
  name: 'full-reload-always',
  handleHotUpdate({ server }) {
    server.ws.send({ type: "full-reload" })
    return []
  },
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), fullReloadAlways],
})
Candelariacandelario answered 9/3, 2023 at 20:50 Comment(0)
C
0

If you want to add a delay before reload then you can use this. This will only do one final reload if multiple file changes happen within the delay duration

// vite.config.js:

import { defineConfig } from 'vite'

let delayTimer = null;
let delay = 700
const fullReloadAlways = {
  handleHotUpdate({ server }) {
    if (delayTimer) {
      clearTimeout(delayTimer);
      delayTimer = null;
    }
    delayTimer = setTimeout(() => {
      server.ws.send({ type: "full-reload" });
    }, delay);
    return [];
  },
};

export default defineConfig({
  plugins: [fullReloadAlways],
})
Cytosine answered 1/10 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.