Skip to content

Commit 19d0355

Browse files
authored
perf: only loads selected locales (#3152)
1 parent cbed761 commit 19d0355

File tree

2 files changed

+35
-10
lines changed

2 files changed

+35
-10
lines changed

assets/modules/i18n.ts

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,45 @@
11
import { type App } from "vue";
22
import { createI18n } from "vue-i18n";
33
import { locale } from "@/stores/settings";
4+
import type { Locale } from "vue-i18n";
45

5-
import messages from "@intlify/unplugin-vue-i18n/messages";
6+
const localesMap = Object.fromEntries(
7+
Object.entries(import.meta.glob("../../locales/*.yml")).map(([path, loadLocale]) => [
8+
path.match(/([\w-]*)\.yml$/)?.[1],
9+
loadLocale,
10+
]),
11+
) as Record<Locale, () => Promise<{ default: Record<string, string> }>>;
612

7-
const defaultLocale = messages?.hasOwnProperty(navigator.language)
8-
? navigator.language
9-
: navigator.language.slice(0, 2);
13+
export const availableLocales = Object.keys(localesMap);
14+
15+
function setI18nLanguage(lang: Locale) {
16+
i18n.global.locale.value = lang;
17+
return lang;
18+
}
19+
20+
const loadedLanguages: string[] = [];
21+
async function loadLanguage(lang: string): Promise<Locale> {
22+
if (i18n.global.locale.value === lang) return setI18nLanguage(lang);
23+
if (loadedLanguages.includes(lang)) return setI18nLanguage(lang);
24+
25+
const messages = await localesMap[lang]();
26+
i18n.global.setLocaleMessage(lang, messages.default);
27+
loadedLanguages.push(lang);
28+
return setI18nLanguage(lang);
29+
}
1030

1131
const i18n = createI18n({
1232
legacy: false,
13-
locale: locale.value || defaultLocale,
14-
fallbackLocale: "en",
15-
messages,
33+
locale: "",
34+
messages: {},
1635
});
1736

18-
watch(locale, (value) => {
19-
i18n.global.locale.value = value || defaultLocale;
37+
watchEffect(() => {
38+
loadLanguage(
39+
locale.value ||
40+
[navigator.language, navigator.language.slice(0, 2)].find((l) => availableLocales.includes(l)) ||
41+
"en",
42+
);
2043
});
2144

2245
export const install = (app: App) => app.use(i18n);

assets/pages/settings.vue

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,9 @@ import {
156156
locale,
157157
} from "@/stores/settings";
158158
159-
const { t, availableLocales } = useI18n();
159+
import { availableLocales } from "@/modules/i18n";
160+
161+
const { t } = useI18n();
160162
161163
setTitle(t("title.settings"));
162164
const { latest, hasUpdate } = useReleases();

0 commit comments

Comments
 (0)