refactor(i18next): streamline fallback translation handling and initi… (#22894)

This commit is contained in:
Wu Tianwei
2025-07-24 14:40:37 +08:00
committed by GitHub
parent de611ab344
commit a8f09ad43f

View File

@@ -50,24 +50,35 @@ export const loadLangResources = async (lang: string) => {
acc[camelCase(NAMESPACES[index])] = mod acc[camelCase(NAMESPACES[index])] = mod
return acc return acc
}, {} as Record<string, any>) }, {} as Record<string, any>)
return resources
}
const getFallbackTranslation = () => {
const resources = NAMESPACES.reduce((acc, ns, index) => {
acc[camelCase(NAMESPACES[index])] = require(`./en-US/${ns}`).default
return acc
}, {} as Record<string, any>)
return { return {
translation: resources, translation: resources,
} }
} }
i18n.use(initReactI18next) if (!i18n.isInitialized) {
.init({ i18n.use(initReactI18next)
lng: undefined, .init({
fallbackLng: 'en-US', lng: undefined,
}) fallbackLng: 'en-US',
resources: {
'en-US': getFallbackTranslation(),
},
})
}
export const changeLanguage = async (lng?: string) => { export const changeLanguage = async (lng?: string) => {
const resolvedLng = lng ?? 'en-US' const resolvedLng = lng ?? 'en-US'
const resources = { const resource = await loadLangResources(resolvedLng)
[resolvedLng]: await loadLangResources(resolvedLng),
}
if (!i18n.hasResourceBundle(resolvedLng, 'translation')) if (!i18n.hasResourceBundle(resolvedLng, 'translation'))
i18n.addResourceBundle(resolvedLng, 'translation', resources[resolvedLng].translation, true, true) i18n.addResourceBundle(resolvedLng, 'translation', resource, true, true)
await i18n.changeLanguage(resolvedLng) await i18n.changeLanguage(resolvedLng)
} }