feat: add modular i18n foundation

This commit is contained in:
duanshuwen
2026-05-26 14:37:32 +08:00
parent a9b00627e2
commit b05d5a72cd
24 changed files with 606 additions and 4 deletions

60
src/i18n/index.ts Normal file
View File

@@ -0,0 +1,60 @@
import { createI18n } from "vue-i18n";
import { isSupportedLocale, resolveInitialLocale } from "./locales.ts";
import { messages } from "./messages.ts";
import { readStoredLocale, writeStoredLocale } from "./storage.ts";
import { defaultLocale } from "./types.ts";
import type { SupportedLocale } from "./types.ts";
import { syncVantLocale } from "./vant.ts";
function getNavigatorLanguages(): string[] {
if (typeof navigator === "undefined") {
return [];
}
const languages = navigator.languages ? [...navigator.languages] : [];
if (languages.length > 0) {
return languages;
}
return navigator.language ? [navigator.language] : [];
}
function setDocumentLanguage(locale: SupportedLocale): void {
if (typeof document === "undefined") {
return;
}
document.documentElement.lang = locale;
}
const initialLocale = resolveInitialLocale({
storedLocale: readStoredLocale(),
navigatorLanguages: getNavigatorLanguages(),
});
syncVantLocale(initialLocale);
setDocumentLanguage(initialLocale);
export const i18n = createI18n({
legacy: false,
locale: initialLocale,
fallbackLocale: defaultLocale,
messages,
});
export function getCurrentLocale(): SupportedLocale {
const locale = i18n.global.locale.value;
return isSupportedLocale(locale) ? locale : defaultLocale;
}
export function setLocale(locale: string): void {
if (!isSupportedLocale(locale)) {
return;
}
i18n.global.locale.value = locale;
writeStoredLocale(locale);
syncVantLocale(locale);
setDocumentLanguage(locale);
}