dify/web/i18n/i18next-config.ts

75 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-05-15 08:51:32 +08:00
'use client'
import i18n from 'i18next'
import { camelCase } from 'lodash-es'
2023-05-15 08:51:32 +08:00
import { initReactI18next } from 'react-i18next'
const requireSilent = async (lang: string, namespace: string) => {
let res
try {
res = (await import(`./${lang}/${namespace}`)).default
}
catch {
res = (await import(`./en-US/${namespace}`)).default
}
return res
}
const NAMESPACES = [
'app-annotation',
'app-api',
'app-debug',
'app-log',
'app-overview',
'app',
'billing',
'common',
'custom',
'dataset-creation',
'dataset-documents',
'dataset-hit-testing',
'dataset-settings',
'dataset',
'education',
'explore',
'layout',
'login',
'plugin-tags',
'plugin',
'register',
'run-log',
'share',
'time',
'tools',
'workflow',
]
2024-02-23 14:31:06 +08:00
export const loadLangResources = async (lang: string) => {
const modules = await Promise.all(NAMESPACES.map(ns => requireSilent(lang, ns)))
const resources = modules.reduce((acc, mod, index) => {
acc[camelCase(NAMESPACES[index])] = mod
return acc
}, {} as Record<string, any>)
return {
translation: resources,
}
}
2023-05-15 08:51:32 +08:00
i18n.use(initReactI18next)
.init({
2023-10-18 16:00:56 +08:00
lng: undefined,
2024-01-23 21:14:53 +08:00
fallbackLng: 'en-US',
2023-05-15 08:51:32 +08:00
})
export const changeLanguage = async (lng?: string) => {
const resolvedLng = lng ?? 'en-US'
const resources = {
[resolvedLng]: await loadLangResources(resolvedLng),
}
if (!i18n.hasResourceBundle(resolvedLng, 'translation'))
i18n.addResourceBundle(resolvedLng, 'translation', resources[resolvedLng].translation, true, true)
await i18n.changeLanguage(resolvedLng)
}
2023-05-15 08:51:32 +08:00
export default i18n