feat: implement initial language resolution for SSR and local storage support

- Added a function to determine the initial language based on server-side rendering and local storage.
- Updated i18n initialization to use the resolved initial language instead of the default.
This commit is contained in:
2026-05-25 14:54:31 +08:00
parent 9bd7cc9b9e
commit 3649bb9300
8 changed files with 70 additions and 7 deletions

View File

@@ -53,6 +53,17 @@ const resources = {
Record<(typeof namespaces)[number], Record<string, unknown>>
>;
function resolveInitialLanguage(): AppLanguage {
// SSR 始终使用默认语言,避免首屏渲染依赖浏览器状态
if (typeof window === "undefined") {
return DEFAULT_LANGUAGE;
}
const stored = window.localStorage.getItem("i18nextLng");
const preferred = normalizeLanguage(stored ?? window.navigator.language);
return preferred;
}
export function syncDocumentLanguage(lang: AppLanguage): void {
if (typeof document === "undefined") return;
@@ -72,6 +83,8 @@ export function syncPreferredLanguage(): void {
}
if (!i18n.isInitialized) {
const initialLng = resolveInitialLanguage();
void i18n.use(initReactI18next).init({
resources,
fallbackLng: DEFAULT_LANGUAGE,
@@ -80,8 +93,7 @@ if (!i18n.isInitialized) {
ns: [...namespaces],
/** 始终先用默认语言完成 SSR / 首次 hydration避免首屏文本不一致 */
load: "languageOnly",
lng: DEFAULT_LANGUAGE,
initImmediate: false,
lng: initialLng,
interpolation: {
escapeValue: false,