frontAnswerer/src/i18n/i18n.ts

92 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-04-20 15:16:22 +00:00
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) {
2025-08-12 01:26:22 +00:00
const detectedLang = langMatch[1].toLowerCase();
return detectedLang;
2025-04-20 15:16:22 +00:00
}
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,
2025-07-23 23:29:22 +00:00
requestOptions: {
cache: "no-store",
},
2025-04-20 15:16:22 +00:00
},
react: {
useSuspense: false, // Отключаем для совместимости с React 18
},
detection: {
order: ["path"], // Только из URL
lookupFromPathIndex: 0,
caches: [], // Не использовать localStorage
},
2025-05-01 13:23:10 +00:00
parseMissingKeyHandler: (key) => {
2025-08-12 01:26:22 +00:00
console.warn("⚠️ Main i18n: Missing translation:", key);
2025-05-01 13:23:10 +00:00
return key; // Вернёт ключ вместо ошибки
},
missingKeyHandler: (lngs, ns, key) => {
2025-08-12 01:26:22 +00:00
console.error("🚨 Main i18n: Missing i18n key:", {
2025-05-01 13:23:10 +00:00
key,
languages: lngs,
namespace: ns,
stack: new Error().stack, // Выведет стек вызовов
});
},
2025-04-20 15:16:22 +00:00
})
.catch((err) => {
2025-08-12 01:26:22 +00:00
console.error("❌ Main i18n: Initialization failed:", err);
2025-04-20 15:16:22 +00:00
});
// 3. Логирование всех событий
i18n.on("languageChanged", (lng) => {
2025-08-12 01:26:22 +00:00
console.log("🔄 Main i18n: Language changed to:", lng);
});
i18n.on("initialized", (options) => {
console.log("🎯 Main i18n: Initialized event fired with options:", options);
2025-04-20 15:16:22 +00:00
});
i18n.on("failedLoading", (lng, ns, msg) => {
2025-08-12 01:26:22 +00:00
console.error(`💥 Main i18n: Failed loading ${lng}.json:`, msg);
2025-07-23 23:29:22 +00:00
// Если не удалось загрузить русский, пробуем английский
if (lng === "ru") {
2025-08-12 01:26:22 +00:00
console.log("🔄 Main i18n: Trying to load English as fallback");
2025-07-23 23:29:22 +00:00
i18n.changeLanguage("en");
}
});
i18n.on("loaded", (loaded) => {
2025-08-12 01:26:22 +00:00
console.log("📦 Main i18n: Translations loaded:", loaded);
2025-07-23 23:29:22 +00:00
});
i18n.on("missingKey", (lngs, namespace, key, res) => {
2025-08-12 01:26:22 +00:00
console.warn("⚠️ Main i18n: Missing key event:", { lngs, namespace, key, res });
2025-04-20 15:16:22 +00:00
});
export default i18n;