react.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import i18next from 'i18next';
  2. import { initReactI18next } from 'react-i18next';
  3. import { LanguageManager } from '@/utils';
  4. import enUS from '../../../web/translation/en-US.json';
  5. const FALLBACK = 'en-US';
  6. const lazyModules = import.meta.glob([
  7. '../../../web/translation/*.json',
  8. '!../../../web/translation/en-US.json',
  9. ]);
  10. function moduleKeyFor(code: string): string {
  11. return `../../../web/translation/${code}.json`;
  12. }
  13. let active: string = LanguageManager.getLanguage();
  14. if (active !== FALLBACK && !Object.prototype.hasOwnProperty.call(lazyModules, moduleKeyFor(active))) {
  15. active = FALLBACK;
  16. }
  17. export async function readyI18n() {
  18. await i18next.use(initReactI18next).init({
  19. lng: active,
  20. fallbackLng: FALLBACK,
  21. resources: { [FALLBACK]: { translation: enUS } },
  22. interpolation: { escapeValue: false, prefix: '{', suffix: '}' },
  23. returnNull: false,
  24. });
  25. if (active !== FALLBACK) {
  26. const loader = lazyModules[moduleKeyFor(active)] as (() => Promise<{ default: Record<string, unknown> }>) | undefined;
  27. if (loader) {
  28. const mod = await loader();
  29. const messages = (mod.default ?? mod) as Record<string, unknown>;
  30. i18next.addResourceBundle(active, 'translation', messages, true, true);
  31. await i18next.changeLanguage(active);
  32. }
  33. }
  34. return i18next;
  35. }
  36. export { i18next as i18n };