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.
30 lines (29 loc) • 1.37 kB
JavaScript
import { getQuery, getCookie } from "h3";
import { interpolate, useTranslationHelper } from "nuxt-i18n-micro-core";
import { useRuntimeConfig } from "#imports";
async function fetchTranslations(locale) {
try {
const translations = await $fetch(`/_locales/general/${locale}/data.json`);
return translations;
} catch (error) {
console.error(`Error loading translation for locale "${locale}":`, error);
return {};
}
}
export const useTranslationServerMiddleware = async (event, defaultLocale, currentLocale) => {
const { getTranslation, loadTranslations, hasGeneralTranslation } = useTranslationHelper();
const config = useRuntimeConfig(event).i18nConfig;
const locale = (currentLocale || event.context.params?.locale || getQuery(event)?.locale || getCookie(event, "user-locale") || event.headers.get("accept-language")?.split(",")[0] || config.fallbackLocale || defaultLocale || "en").toString();
if (!hasGeneralTranslation(locale)) {
const translations = await fetchTranslations(locale);
await loadTranslations(locale, translations);
}
function t(key, params, defaultValue) {
let translation = getTranslation(locale, "index", key);
if (!translation) {
translation = defaultValue || key;
}
return typeof translation === "string" && params ? interpolate(translation, params) : translation;
}
return t;
};