Created
December 18, 2022 11:31
-
-
Save nkoehring/08531494ef97d0d36fb82630c2481e5e to your computer and use it in GitHub Desktop.
Automatically load all necessary namespaces when switching the locale in typesafe-i18n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { watch } from 'vue' | |
import type { Locales, Namespaces } from '@i18n/i18n-types' | |
import { isNamespace } from '@i18n/i18n-util' | |
import { loadNamespaceAsync } from '@i18n/i18n-util.async' | |
import { typesafeI18n } from '@i18n/i18n-vue' | |
import { useRoute } from 'vue-router/auto' | |
function loadNamespaces(locale: Locales, namespaces: Namespaces[], setLocale: (l: Locales) => void) { | |
console.debug('loading locale namespaces', namespaces) | |
const loaders = namespaces.map((l) => loadNamespaceAsync(locale, l)) | |
return Promise.all(loaders).then(() => setLocale(locale)) | |
} | |
/** | |
* Load locale namespaces given in route meta information and provide i18nObject. | |
* | |
* Route meta information is used and the following properties are supported: | |
* noGlobalLocales: boolean // do not load app-wide locales, default: false | |
* locales: string[] // additional namespaces to load, default [] | |
*/ | |
export default function useLocales() { | |
const { locale, setLocale, LL } = typesafeI18n() | |
const route = useRoute() | |
const namespaces: Namespaces[] = [] | |
if (route.meta.noGlobalLocales !== true) { | |
namespaces.push('global') | |
} | |
if (Array.isArray(route.meta.locales)) { | |
route.meta.locales.forEach((l) => { | |
if (isNamespace(l)) namespaces.push(l) | |
else console.error('Route', route, 'asked for non-existent locale namespace', l) | |
}) | |
} | |
loadNamespaces(locale.value, namespaces, setLocale).then(() => { | |
watch(locale, (newLocale) => loadNamespaces(newLocale, namespaces, setLocale)) | |
}) | |
return { locale, setLocale, LL } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment