import i18next, { TOptions, StringMap, TFunction } from 'i18next'; import ChainedBackend from 'i18next-chained-backend'; import { I18nTekoMultiLangBackend } from '@multi-lang/teko-multi-language'; import { initReactI18next } from 'react-i18next'; import resourcesToBackend from 'i18next-resources-to-backend'; import { getCurrentLanguage } from '@tempi/utils'; export type LangType = { [key: string]: { [key: string]: string }; }; const { env } = window?.config || {}; const mapEnv = { dev: 'development', stag: 'staging', production: 'production', }; const { languageServiceCode, defaultLanguage = 'vi' } = window?.config || {}; const lng = getCurrentLanguage(); document.documentElement.lang = lng; const getDefaultResources = () => { return defaultLanguage === 'en' ? import('./locales/en/translation.json') : import('./locales/vi/translation.json'); }; i18next .use(initReactI18next) // passes i18n down to react-i18next .use(ChainedBackend) // Use Teko multi language plugin .init({ lng, fallbackLng: defaultLanguage, interpolation: { escapeValue: false, }, initImmediate: false, // Must pass for synchronize init backend: languageServiceCode ? { backends: [ I18nTekoMultiLangBackend, resourcesToBackend(() => getDefaultResources()), ], backendOptions: [ { env: mapEnv[env], // Environment serviceCode: languageServiceCode, // Service ID expirationTime: 10000, // TTL of cached languagein milisecond. Default is 10 minutes }, ], } : { backends: [resourcesToBackend(() => getDefaultResources())], }, }) .then(async () => { try { const overrideResources = (await getDefaultResources()).default; const resources = i18next.getResourceBundle(lng, 'translation'); i18next.addResourceBundle( lng, 'translation', { ...overrideResources, ...resources }, true, ); } catch (e) { console.error(e); } }); export const t = ( keys: string | string[], options?: TOptions, ): string => { const text = i18next.t(keys, { ...options, interpolation: { escapeValue: false }, }); // debugger; return text || (keys as string); }; export const changeLanguage = async (lng: string): Promise => { return i18next.changeLanguage(lng); };