我有一个用Vite配置的react项目。
热重加载很好,但是我使用react-i18next来支持多语言,这是我的结构:
public
-> en
-> translation.json
-> ru
-> translation.json当我更改translation.json文件时,Vite不查看它,我必须刷新页面才能看到更改。
有没有一种方法可以让Vite监视public目录中的所有文件?
发布于 2021-10-19 09:49:02
你可以用一个插件来实现这一点。
我在第一个回答中犯了一个错误,它应该是一个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的回购:
结果说明

发布于 2022-02-08 15:18:47
我修改了flydev的答案,这样它就可以在不重新加载整个页面的情况下重新加载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()并不会触发翻译热重加载
https://stackoverflow.com/questions/69626090
复制相似问题