-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathi18n.ts
80 lines (76 loc) · 2.19 KB
/
i18n.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type { CompileError, MessageContext } from "vue-i18n";
import { createI18n } from "vue-i18n";
import { IntlMessageFormat } from "intl-messageformat";
export default defineNuxtPlugin(({ vueApp }) => {
function checkDefaultLanguage() {
let matched = null;
const languages = Object.getOwnPropertyNames(messages());
const matching = navigator.languages.filter(lang => languages.some(l => l.toLowerCase() === lang.toLowerCase()));
if (matching.length > 0) {
matched = matching[0];
}
if (!matched) {
languages.forEach(lang => {
const languagePartials = navigator.language.split("-")[0];
if (lang.toLowerCase() === languagePartials) {
matched = lang;
}
});
}
return matched;
}
const preferences = useViewPreferences();
const i18n = createI18n({
fallbackLocale: "en",
globalInjection: true,
legacy: false,
locale: preferences.value.language || checkDefaultLanguage() || "en",
messageCompiler,
messages: messages(),
});
vueApp.use(i18n);
return {
provide: {
i18nGlobal: i18n.global,
},
};
});
export const messages = () => {
const messages: Record<string, any> = {};
const modules = import.meta.glob("~//locales/**.json", { eager: true });
for (const path in modules) {
const key = path.slice(9, -5);
messages[key] = modules[path];
}
return messages;
};
export const messageCompiler: (
message: String | any,
{
locale,
key,
onError,
}: {
locale: any;
key: any;
onError: any;
}
) => (ctx: MessageContext) => unknown = (message, { locale, key, onError }) => {
if (typeof message === "string") {
/**
* You can tune your message compiler performance more with your cache strategy or also memoization at here
*/
const formatter = new IntlMessageFormat(message, locale);
return (ctx: MessageContext) => {
return formatter.format(ctx.values);
};
} else {
/**
* for AST.
* If you would like to support it,
* You need to transform locale messages such as `json`, `yaml`, etc. with the bundle plugin.
*/
onError && onError(new Error("not support for AST") as CompileError);
return () => key;
}
};