Ben Lin
2024-04-25 fa77d6fcb0b770edc33c65ee9b947c34af2c3bf9
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
import type { App } from 'vue';
import type { I18n, I18nOptions } from 'vue-i18n';
 
import { createI18n } from 'vue-i18n';
import { setHtmlPageLang, setLoadLocalePool } from './helper';
import { localeSetting } from '/@/settings/localeSetting';
import { useLocaleStoreWithOut } from '/@/store/modules/locale';
 
const { fallback, availableLocales } = localeSetting;
 
export let i18n: ReturnType<typeof createI18n>;
 
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getLangJson(enObj, cnObj) {
  const json = {};
  if (typeof enObj === 'object') {
    for (const key in enObj) {
      if (
        Object.prototype.hasOwnProperty.call(enObj, key) &&
        Object.prototype.hasOwnProperty.call(cnObj, key)
      ) {
        const en = enObj[key];
        const cn = cnObj[key];
        if (typeof en === 'object') {
          json[key] = getLangJson(en, cn); // 递归处理子对象
        } else {
          json[key] = {};
          json[key].en = en;
          json[key].cn = cn;
        }
      }
    }
  }
  return json;
}
 
async function createI18nOptions(): Promise<I18nOptions> {
  const localeStore = useLocaleStoreWithOut();
  const locale = localeStore.getLocale;
  const defaultLocal = await import(`./lang/${locale}.ts`);
  const message = defaultLocal.default?.apiMessage ?? {};
  //生成语言包文件
  // const en = (await import(`./lang/${'en'}.ts`)).default?.message;
  // const cn = defaultLocal.default?.message;
  // let lang = getLangJson(en, cn);
 
  setHtmlPageLang(locale);
  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale);
  });
 
  return {
    legacy: false,
    locale,
    fallbackLocale: fallback,
    messages: {
      [locale]: message,
    },
    availableLocales: availableLocales,
    sync: true, //If you don’t want to inherit locale from global scope, you need to set sync of i18n component option to false.
    silentTranslationWarn: true, // true - warning off
    missingWarn: false,
    silentFallbackWarn: true,
  };
}
 
// setup i18n instance with glob
export async function setupI18n(app: App) {
  const options = await createI18nOptions();
  i18n = createI18n(options) as I18n;
  app.use(i18n);
}