简体   繁体   中英

How to watch public directory in Vite project for hot-reload?

I have a react project configured with Vite.
Hot reload works great, but I use react-i18next for multiple language support and this is my structure:

public
  -> en
    -> translation.json
  -> ru
    -> translation.json

When I change the translation.json files, Vite doesn't watch it, and I have to refresh the page to see the changes.

Is there a way to tell Vite to watch all the files in the public directory?

You can achieve that with a plugin. In vite.config.js add this plugin :

function CustomHmr() {
  return {
    name: 'custom-hmr',
    enforce: "pre",

    handleHotUpdate({ file, server }) {
      if (file.endsWith('.json')) {
        // send event 
        server.ws.send({
            type: 'update',
            path: '*'
        });
      }
    }
  }
}

then reference it in the config:

{
  plugins: [
    CustomHmr()   <---  custom plugin
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM