UNPKG

nuxt-i18n-micro

Version:

Nuxt I18n Micro is a lightweight, high-performance internationalization module for Nuxt, designed to handle multi-language support with minimal overhead, fast build times, and efficient runtime performance.

69 lines (68 loc) 2.8 kB
import { getEnabledLocaleCodes } from "@i18n-micro/utils/active-locales"; import { getHashCookieName, getLocaleCookieName, getLocaleCookieOptions } from "@i18n-micro/utils/cookie"; import { resolveI18nConfigWithRuntimeOverrides } from "@i18n-micro/utils/runtime-config"; import { useCookie, useNuxtApp, useState } from "#app"; import { getI18nConfig } from "#build/i18n.strategy.mjs"; export function useI18nLocale() { const nuxtApp = useNuxtApp(); const i18nConfig = resolveI18nConfigWithRuntimeOverrides(nuxtApp.$getI18nConfig?.() ?? getI18nConfig()); const validLocales = getEnabledLocaleCodes(i18nConfig.locales); const localeState = useState("i18n-locale", () => null); const localeCookieName = getLocaleCookieName(i18nConfig); const hashCookieName = getHashCookieName(i18nConfig); const localeCookie = localeCookieName ? useCookie(localeCookieName, getLocaleCookieOptions()) : { value: null }; const hashCookie = hashCookieName ? useCookie(hashCookieName, getLocaleCookieOptions()) : { value: null }; const syncLocale = (locale) => { if (!locale) return; if (hashCookieName) hashCookie.value = locale; if (localeCookieName) localeCookie.value = locale; }; const setLocale = (locale) => { if (locale) { localeState.value = locale; syncLocale(locale); } }; const getPreferredLocale = () => { const preferred = localeState.value ?? (i18nConfig.hashMode ? hashCookie.value : localeCookie.value); return preferred && validLocales.includes(preferred) ? preferred : null; }; const getLocale = () => { return localeState.value ?? (i18nConfig.hashMode ? hashCookie.value : localeCookie.value) ?? null; }; const getLocaleWithServerFallback = (serverLocale) => { return localeState.value ?? localeCookie.value ?? serverLocale ?? null; }; const getEffectiveLocale = (route, getLocaleFromRoute) => { if (i18nConfig.hashMode && localeState.value !== null && localeState.value !== void 0) return localeState.value; return getLocaleFromRoute(route); }; const resolveInitialLocale = (options) => { let locale = localeState.value; if (!locale && options.serverLocale) locale = options.serverLocale; if (!locale) locale = options.getLocaleFromRoute(options.route); if (locale && !localeState.value) { if (import.meta.server) { localeState.value = locale; } else { setLocale(locale); } } return locale ?? ""; }; const isValidLocale = (locale) => !!locale && validLocales.includes(locale); return { locale: localeState, localeCookie, hashCookie, getPreferredLocale, getLocale, getLocaleWithServerFallback, getEffectiveLocale, resolveInitialLocale, setLocale, syncLocale, isValidLocale, validLocales }; }