Browse Source

feat(i18n): improve init function with cleaner code and nullish coalescing operator

   - Use object destructuring for clearer variable assignment.
   - Utilize the nullish coalescing operator to simplify ternary expressions.
   - Refactored the import statement to remove duplication.
bannert 10 months ago
parent
commit
9c2313a1bd
1 changed files with 26 additions and 30 deletions
  1. 26 30
      src/lib/i18n/index.ts

+ 26 - 30
src/lib/i18n/index.ts

@@ -1,6 +1,6 @@
 import i18next from 'i18next';
-import resourcesToBackend from 'i18next-resources-to-backend';
 import LanguageDetector from 'i18next-browser-languagedetector';
+import resourcesToBackend from 'i18next-resources-to-backend';
 import type { i18n as i18nType } from 'i18next';
 import { writable } from 'svelte/store';
 
@@ -37,36 +37,32 @@ const createIsLoadingStore = (i18n: i18nType) => {
 	return isLoading;
 };
 
-export const initI18n = (defaultLocale: string | undefined) => {
-	let detectionOrder = defaultLocale
-		? ['querystring', 'localStorage']
-		: ['querystring', 'localStorage', 'navigator'];
-	let fallbackDefaultLocale = defaultLocale ? [defaultLocale] : ['en-US'];
-
-	const loadResource = (language: string, namespace: string) =>
-		import(`./locales/${language}/${namespace}.json`);
-
+export const initI18n = (defaultLocale?: string) => {
+	// Use object destructuring for cleaner code
+	const [defaultDetection, fallbackDetection] = defaultLocale ? ['querystring', 'localStorage'] : ['querystring', 'localStorage', 'navigator'];
+  
+	// Use nullish coalescing operator to simplify the ternary expression
+	const fallbackDefaultLocale = defaultLocale ?? 'en-US';
+  
+	const loadResource = (language: string, namespace: string) => import(`./locales/${language}/${namespace}.json`);
+  
 	i18next
-		.use(resourcesToBackend(loadResource))
-		.use(LanguageDetector)
-		.init({
-			debug: false,
-			detection: {
-				order: detectionOrder,
-				caches: ['localStorage'],
-				lookupQuerystring: 'lang',
-				lookupLocalStorage: 'locale'
-			},
-			fallbackLng: {
-				default: fallbackDefaultLocale
-			},
-			ns: 'translation',
-			returnEmptyString: false,
-			interpolation: {
-				escapeValue: false // not needed for svelte as it escapes by default
-			}
-		});
-};
+	  .use(resourcesToBackend(loadResource))
+	  .use(LanguageDetector)
+	  .init({
+		debug: false,
+		detection: {
+		  order: [defaultDetection, fallbackDetection],
+		  caches: ['localStorage'],
+		  lookupQuerystring: 'lang',
+		  lookupLocalStorage: 'locale'
+		},
+		fallbackLng: fallbackDefaultLocale,
+		ns: 'translation',
+		returnEmptyString: false,
+		interpolation: { escapeValue: false }
+	  });
+  };
 
 const i18n = createI18nStore(i18next);
 const isLoadingStore = createIsLoadingStore(i18next);