如何查看Vite项目中的public目录进行热重载?

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

我有一个用 Vite 配置的 React 项目。
热重载效果很好,但我使用 react-i18next 来支持多语言,这是我的结构:

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

当我更改translation.json文件时,Vite没有看到它,我必须刷新页面才能看到更改。

有没有办法让Vite监视public目录下的所有文件?

您可以使用插件实现。

我的第一个回答有误,应该是 full-reload 事件而不是 update 事件

export default function CustomHmr() {
    return {
      name: 'custom-hmr',
      enforce: 'post',
      // HMR
      handleHotUpdate({ file, server }) {
        if (file.endsWith('.json')) {
          console.log('reloading json file...');
  
          server.ws.send({
            type: 'full-reload',          
            path: '*'
          });
        }
      },
    }
}

然后在vite.config.js中添加插件:

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

我在 Github 上给你做了一个 repo,并提供了一个工作示例:

结果说明

我已经修改了 flydev 的答案,这样它就可以 hot-reload 依赖于 i18n 的组件而无需重新加载整个页面。 (目前在打字稿项目中使用)

import { PluginOption } from "vite";

export default function I18nHotReload(): PluginOption {
  return {
    name: 'i18n-hot-reload',
    handleHotUpdate({ file, server }) {
      if (file.includes('locales') && file.endsWith('.json')) {
        console.log('Locale file updated')
        server.ws.send({
          type: "custom",
          event: "locales-update",
        });
      }
    },
  }
}

然后添加到vite的插件中:

plugins: [
    ...,
    i18nHotReload(),
]

然后在代码可以到达的任何地方添加侦听器(我在 i18n 初始配置文件中使用它)

if (import.meta.hot) {
  import.meta.hot.on('locales-update', () => {
    i18n.reloadResources().then(() => {
      i18n.changeLanguage(i18n.language)
    })
  })
}

i18n.reloadResources() alone doesn't trigger the translations hot reload