You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

2 years ago
  1. // 多组件库的国际化和本地项目国际化兼容
  2. import { App, WritableComputedRef } from "vue";
  3. import { storageLocal } from "@pureadmin/utils";
  4. import { type I18n, createI18n } from "vue-i18n";
  5. // element-plus国际化
  6. import enLocale from "element-plus/lib/locale/lang/en";
  7. import zhLocale from "element-plus/lib/locale/lang/zh-cn";
  8. function siphonI18n(prefix = "zh-CN") {
  9. return Object.fromEntries(
  10. Object.entries(
  11. import.meta.glob("../../locales/*.y(a)?ml", { eager: true })
  12. ).map(([key, value]: any) => {
  13. const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1];
  14. return [matched, value.default];
  15. })
  16. )[prefix];
  17. }
  18. export const localesConfigs = {
  19. zh: {
  20. ...siphonI18n("zh-CN"),
  21. ...zhLocale
  22. },
  23. en: {
  24. ...siphonI18n("en"),
  25. ...enLocale
  26. }
  27. };
  28. /**
  29. * locales文件夹下文件进行国际化匹配
  30. * @param message message
  31. * @returns message
  32. */
  33. export function transformI18n(message: any = "") {
  34. if (!message) {
  35. return "";
  36. }
  37. // 处理存储动态路由的title,格式 {zh:"",en:""}
  38. if (typeof message === "object") {
  39. const locale: string | WritableComputedRef<string> | any =
  40. i18n.global.locale;
  41. return message[locale?.value];
  42. }
  43. const key = message.match(/(\S*)\./)?.[1];
  44. if (key && Object.keys(siphonI18n("zh-CN")).includes(key)) {
  45. return i18n.global.t.call(i18n.global.locale, message);
  46. } else if (!key && Object.keys(siphonI18n("zh-CN")).includes(message)) {
  47. // 兼容非嵌套形式的国际化写法
  48. return i18n.global.t.call(i18n.global.locale, message);
  49. } else {
  50. return message;
  51. }
  52. }
  53. /** 此函数只是配合i18n Ally插件来进行国际化智能提示,并无实际意义(只对提示起作用),如果不需要国际化可删除 */
  54. export const $t = (key: string) => key;
  55. export const i18n: I18n = createI18n({
  56. legacy: false,
  57. locale:
  58. storageLocal().getItem<StorageConfigs>("responsive-locale")?.locale ?? "zh",
  59. fallbackLocale: "en",
  60. messages: localesConfigs
  61. });
  62. export function useI18n(app: App) {
  63. app.use(i18n);
  64. }