react.ts 1.5 KB

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