index.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. i18next
  34. .use(
  35. resourcesToBackend(
  36. (language: string, namespace: string) => import(`./locales/${language}/${namespace}.json`)
  37. )
  38. )
  39. .use(LanguageDetector)
  40. .init({
  41. debug: true,
  42. detection: {
  43. order: ['querystring', 'localStorage', 'navigator'],
  44. caches: ['localStorage'],
  45. lookupQuerystring: 'lang',
  46. lookupLocalStorage: 'locale'
  47. },
  48. fallbackLng: {
  49. default: ['en']
  50. },
  51. ns: 'translation',
  52. interpolation: {
  53. escapeValue: false // not needed for svelte as it escapes by default
  54. }
  55. });
  56. const i18n = createI18nStore(i18next);
  57. const isLoadingStore = createIsLoadingStore(i18next);
  58. export const getLanguages = async () => {
  59. const languages = (await import(`./locales/languages.json`)).default;
  60. return languages;
  61. };
  62. export default i18n;
  63. export const isLoading = isLoadingStore;