index.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { App } from "vue";
  2. import axios from "axios";
  3. import { loadEnv } from "@build/index";
  4. let config: object = {};
  5. const { VITE_PUBLIC_PATH } = loadEnv();
  6. const setConfig = (cfg?: unknown) => {
  7. config = Object.assign(config, cfg);
  8. };
  9. const getConfig = (key?: string): ServerConfigs => {
  10. if (typeof key === "string") {
  11. const arr = key.split(".");
  12. if (arr && arr.length) {
  13. let data = config;
  14. arr.forEach(v => {
  15. if (data && typeof data[v] !== "undefined") {
  16. data = data[v];
  17. } else {
  18. data = null;
  19. }
  20. });
  21. return data;
  22. }
  23. }
  24. return config;
  25. };
  26. // 获取项目动态全局配置
  27. export const getServerConfig = async (app: App): Promise<undefined> => {
  28. app.config.globalProperties.$config = getConfig();
  29. return axios({
  30. baseURL: "",
  31. method: "get",
  32. url: `${VITE_PUBLIC_PATH}serverConfig.json`
  33. })
  34. .then(({ data: config }) => {
  35. let $config = app.config.globalProperties.$config;
  36. // 自动注入项目配置
  37. if (app && $config && typeof config === "object") {
  38. $config = Object.assign($config, config);
  39. app.config.globalProperties.$config = $config;
  40. // 设置全局配置
  41. setConfig($config);
  42. }
  43. // 设置全局baseURL
  44. app.config.globalProperties.$baseUrl = $config.baseURL;
  45. return $config;
  46. })
  47. .catch(() => {
  48. throw "请在public文件夹下添加serverConfig.json配置文件";
  49. });
  50. };
  51. export { getConfig, setConfig };