frontAnswerer/src/i18n/i18n.ts
2025-07-29 00:23:25 +03:00

93 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";
// 1. Функция для принудительного определения языка из URL
const getLanguageFromURL = (): string => {
const path = window.location.pathname;
// Регулярка для /en/ /ru/ /uz/ в начале пути
const langMatch = path.match(/^\/(en|ru|uz)(\/|$)/i);
if (langMatch) {
//console.log("Язык из URL:", langMatch[1]);
return langMatch[1].toLowerCase();
}
//console.log('Язык не указан в URL, используем "ru"');
return "ru"; // Жёсткий фолбэк
};
// 2. Конфиг с полной отладкой
i18n
.use(Backend)
.use(initReactI18next)
.init({
lng: getLanguageFromURL(), // Принудительно из URL
fallbackLng: "ru",
supportedLngs: ["en", "ru", "uz"],
debug: true,
interpolation: {
escapeValue: false,
},
backend: {
loadPath: "/locales/{{lng}}.json",
allowMultiLoading: false,
requestOptions: {
cache: "no-store",
},
},
react: {
useSuspense: false, // Отключаем для совместимости с React 18
},
detection: {
order: ["path"], // Только из URL
lookupFromPathIndex: 0,
caches: [], // Не использовать localStorage
},
parseMissingKeyHandler: (key) => {
console.warn("Missing translation:", key);
return key; // Вернёт ключ вместо ошибки
},
missingKeyHandler: (lngs, ns, key) => {
console.error("🚨 Missing i18n key:", {
key,
languages: lngs,
namespace: ns,
stack: new Error().stack, // Выведет стек вызовов
});
},
})
.then(() => {
console.log("i18n initialized. Current language:", i18n.language);
console.log("Loading translations from:", `/locales/${i18n.language}.json`);
})
.catch((err) => {
console.error("Ошибка i18n:", err);
});
// 3. Логирование всех событий
i18n.on("languageChanged", (lng) => {
console.log("Язык изменён на:", lng);
});
i18n.on("failedLoading", (lng, ns, msg) => {
console.error(`Ошибка загрузки ${lng}.json:`, msg);
// Если не удалось загрузить русский, пробуем английский
if (lng === "ru") {
console.log("Пробуем загрузить английский язык как fallback");
i18n.changeLanguage("en");
}
});
i18n.on("loaded", (loaded) => {
console.log("Переводы загружены:", loaded);
});
i18n.on("missingKey", (lngs, namespace, key, res) => {
console.warn("Отсутствует ключ перевода:", { lngs, namespace, key, res });
});
export default i18n;