index.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // 多组件库的国际化和本地项目国际化兼容
  2. import { App } from "vue";
  3. import { set } from "lodash-es";
  4. import { createI18n } from "vue-i18n";
  5. import { localesConfigs } from "./config";
  6. import { storageLocal } from "/@/utils/storage";
  7. /**
  8. * 国际化转换工具函数
  9. * @param message message
  10. * @param isI18n 如果true,获取对应的消息,否则返回本身
  11. * @returns message
  12. */
  13. export function transformI18n(message: string | object = "", isI18n = false) {
  14. if (!message) {
  15. return "";
  16. }
  17. // 处理存储动态路由的title,格式 {zh:"",en:""}
  18. if (typeof message === "object") {
  19. return message[i18n.global?.locale];
  20. }
  21. if (isI18n) {
  22. //@ts-ignore
  23. return i18n.global.tc.call(i18n.global, message);
  24. } else {
  25. return message;
  26. }
  27. }
  28. /**
  29. * 从模块中抽取国际化
  30. * @param langs 存放国际化模块
  31. * @param prefix 语言 默认 zh-CN
  32. * @returns obj 格式:{模块名.**}
  33. */
  34. export function siphonI18n(
  35. langs: Record<string, Record<string, any>>,
  36. prefix = "zh-CN"
  37. ) {
  38. const langsObj: Recordable = {};
  39. Object.keys(langs).forEach((key: string) => {
  40. let fileName = key.replace(`./${prefix}/`, "").replace(/^\.\//, "");
  41. fileName = fileName.substring(0, fileName.lastIndexOf("."));
  42. const keyList = fileName.split("/");
  43. const moduleName = keyList.shift();
  44. const objKey = keyList.join(".");
  45. const langFileModule = langs[key].default;
  46. if (moduleName) {
  47. if (objKey) {
  48. set(langsObj, moduleName, langsObj[moduleName] || {});
  49. set(langsObj[moduleName], objKey, langFileModule);
  50. } else {
  51. set(langsObj, moduleName, langFileModule || {});
  52. }
  53. }
  54. });
  55. return langsObj;
  56. }
  57. // 此函数只是配合i18n Ally插件来进行国际化智能提示,并无实际意义(只对提示起作用),如果不需要国际化可删除
  58. export const $t = (key: string) => key;
  59. export const i18n = createI18n({
  60. locale: storageLocal.getItem("responsive-locale")?.locale ?? "zh",
  61. fallbackLocale: "en",
  62. messages: localesConfigs
  63. });
  64. export function usI18n(app: App) {
  65. app.use(i18n);
  66. }