index.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import i18next from 'i18next';
  2. import resourcesToBackend from 'i18next-resources-to-backend';
  3. import LanguageDetector from 'i18next-browser-languagedetector';
  4. import type { i18n as i18nType } from 'i18next';
  5. import { writable } from 'svelte/store';
  6. const createI18nStore = (i18n: i18nType) => {
  7. const i18nWritable = writable(i18n);
  8. i18n.on('initialized', () => {
  9. i18nWritable.set(i18n);
  10. });
  11. i18n.on('loaded', () => {
  12. i18nWritable.set(i18n);
  13. });
  14. i18n.on('added', () => i18nWritable.set(i18n));
  15. i18n.on('languageChanged', () => {
  16. i18nWritable.set(i18n);
  17. });
  18. return i18nWritable;
  19. };
  20. const createIsLoadingStore = (i18n: i18nType) => {
  21. const isLoading = writable(false);
  22. // if loaded resources are empty || {}, set loading to true
  23. i18n.on('loaded', (resources) => {
  24. // console.log('loaded:', resources);
  25. Object.keys(resources).length !== 0 && isLoading.set(false);
  26. });
  27. // if resources failed loading, set loading to true
  28. i18n.on('failedLoading', () => {
  29. isLoading.set(true);
  30. });
  31. return isLoading;
  32. };
  33. export const initI18n = (defaultLocale: string | undefined) => {
  34. let detectionOrder = defaultLocale
  35. ? ['querystring', 'localStorage']
  36. : ['querystring', 'localStorage', 'navigator'];
  37. let fallbackDefaultLocale = defaultLocale ? [defaultLocale] : ['en-US'];
  38. const loadResource = (language: string, namespace: string) =>
  39. import(`./locales/${language}/${namespace}.json`);
  40. i18next
  41. .use(resourcesToBackend(loadResource))
  42. .use(LanguageDetector)
  43. .init({
  44. debug: false,
  45. detection: {
  46. order: detectionOrder,
  47. caches: ['localStorage'],
  48. lookupQuerystring: 'lang',
  49. lookupLocalStorage: 'locale'
  50. },
  51. fallbackLng: {
  52. default: fallbackDefaultLocale
  53. },
  54. ns: 'translation',
  55. returnEmptyString: false,
  56. interpolation: {
  57. escapeValue: false // not needed for svelte as it escapes by default
  58. }
  59. });
  60. };
  61. const i18n = createI18nStore(i18next);
  62. const isLoadingStore = createIsLoadingStore(i18next);
  63. export const getLanguages = async () => {
  64. const languages = (await import(`./locales/languages.json`)).default;
  65. return languages;
  66. };
  67. export default i18n;
  68. export const isLoading = isLoadingStore;