I've modified flydev's answer so that it can hot-reload the i18n-dependent components without reloading the whole page. (Currently using in a typescript project)
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",
});
}
},
}
}
Then adding it to the vite's plugins:
plugins: [
...,
i18nHotReload(),
]
And then adding the listener anywhere your code can reach (I'm using it in the i18n initial config file)
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