Uecko_ERP/packages/i18n/src/i18n.ts

58 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-11-28 15:00:18 +00:00
import i18next, { type i18n } from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
let hasInit = false;
export const initI18Next = () => {
if (hasInit) return i18next;
i18next
.use(LanguageDetector)
.use(initReactI18next)
.init({
detection: { order: ["navigator"] },
debug: false,
fallbackLng: "es",
interpolation: { escapeValue: false },
});
hasInit = true;
return i18next;
};
/**
* Registra dinámicamente traducciones de un módulo.
*
* Cada módulo tendrá su propio namespace.
*
* idempotente: si el bundle ya existe, no se vuelve a añadir.
*/
export const registerTranslations = (
moduleName: string,
locale: string,
resources: Record<string, unknown>
): void => {
if (!hasInit) {
throw new Error("i18n not initialized. Call initI18Next() first.");
}
const ns = moduleName;
const alreadyExists = i18next.hasResourceBundle(locale, ns);
if (!alreadyExists) {
i18next.addResourceBundle(locale, ns, resources, true, true);
}
};
/**
* Acceso al `t()` global por si se necesita en librerías de backend.
*/
export const t = (...args: Parameters<i18n["t"]>) => {
if (!hasInit) {
throw new Error("i18n not initialized. Call initI18Next() first.");
}
return i18next.t(...args);
};