Sanakey
2024-08-21 7b684b71e37e765d8047b30d53691dd88bd70000
src/utils/env.ts
@@ -1,41 +1,82 @@
import type { GlobEnvConfig } from '#/config';
import pkg from '../../package.json';
import { API_ADDRESS } from '@/enums/cacheEnum';
export function getCommonStoragePrefix() {
  const { VITE_GLOB_APP_TITLE } = getAppEnvConfig();
  return `${VITE_GLOB_APP_TITLE.replace(/\s/g, '_')}__${getEnv()}`.toUpperCase();
}
// Generate cache key according to version
export function getStorageShortName() {
  return `${getCommonStoragePrefix()}${`__${pkg.version}`}__`.toUpperCase();
}
const getVariableName = (title: string) => {
  function strToHex(str: string) {
    const result: string[] = [];
    for (let i = 0; i < str.length; ++i) {
      const hex = str.charCodeAt(i).toString(16);
      result.push(('000' + hex).slice(-4));
    }
    return result.join('').toUpperCase();
  }
  return `__PRODUCTION__${strToHex(title) || '__APP'}__CONF__`.toUpperCase().replace(/\s/g, '');
};
export function getAppEnvConfig() {
  const ENV_NAME = getVariableName(import.meta.env.VITE_GLOB_APP_TITLE);
  const ENV = import.meta.env.DEV
    ? // Get the global configuration (the configuration will be extracted independently when packaging)
      (import.meta.env as unknown as GlobEnvConfig)
    : (window[ENV_NAME] as unknown as GlobEnvConfig);
  const { VITE_GLOB_APP_TITLE, VITE_GLOB_API_URL_PREFIX, VITE_GLOB_UPLOAD_URL } = ENV;
  let { VITE_GLOB_API_URL } = ENV;
  if (localStorage.getItem(API_ADDRESS)) {
    const address = JSON.parse(localStorage.getItem(API_ADDRESS) || '{}');
    if (address?.key) VITE_GLOB_API_URL = address?.val;
  }
  return {
    VITE_GLOB_APP_TITLE,
    VITE_GLOB_API_URL,
    VITE_GLOB_API_URL_PREFIX,
    VITE_GLOB_UPLOAD_URL,
  };
}
/**
 * @description: 开发模式
 * @description: Development mode
 */
export const devMode = 'development';
/**
 * @description: 生产模式
 * @description: Production mode
 */
export const prodMode = 'production';
/**
 * @description: 获取环境变量
 * @param {type}
 * @description: Get environment variables
 * @returns:
 * @example:
 */
export const getEnv = (): string => import.meta.env.MODE;
export function getEnv(): string {
  return import.meta.env.MODE;
}
/**
 * @description: 是否是开发模式
 * @param {type}
 * @description: Is it a development mode
 * @returns:
 * @example:
 */
export const isDevMode = (): boolean => import.meta.env.DEV;
export function isDevMode(): boolean {
  return import.meta.env.DEV;
}
/**
 * @description: 是否是生产模式模式
 * @param {type}
 * @description: Is it a production mode
 * @returns:
 * @example:
 */
export const isProdMode = (): boolean => import.meta.env.PROD;
/**
 * @description: 是否开启mock
 * @param {type}
 * @returns:
 * @example:
 */
export const isUseMock = (): boolean => import.meta.env.VITE_USE_MOCK === 'true';
export function isProdMode(): boolean {
  return import.meta.env.PROD;
}