Blame view

src/utils/env.ts 1.99 KB
Vben authored
1
import type { GlobEnvConfig } from '/#/config';
Vben authored
2
import pkg from '../../package.json';
3
4

const getVariableName = (title: string) => {
5
6
7
8
9
10
11
12
13
14
  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, '');
15
};
Vben authored
16
17
export function getCommonStoragePrefix() {
vben authored
18
19
  const { VITE_GLOB_APP_TITLE } = getAppEnvConfig();
  return `${VITE_GLOB_APP_TITLE.replace(/\s/g, '_')}__${getEnv()}`.toUpperCase();
20
}
21
Vben authored
22
23
// Generate cache key according to version
export function getStorageShortName() {
24
25
26
27
  return `${getCommonStoragePrefix()}${`__${pkg.version}`}__`.toUpperCase();
}

export function getAppEnvConfig() {
vben authored
28
  const ENV_NAME = getVariableName(import.meta.env.VITE_GLOB_APP_TITLE);
29
Vben authored
30
  const ENV = (import.meta.env.DEV
31
    ? // Get the global configuration (the configuration will be extracted independently when packaging)
Vben authored
32
33
      (import.meta.env as unknown as GlobEnvConfig)
    : window[ENV_NAME as any]) as unknown as GlobEnvConfig;
34
vben authored
35
36
  const { VITE_GLOB_APP_TITLE, VITE_GLOB_API_URL, VITE_GLOB_API_URL_PREFIX, VITE_GLOB_UPLOAD_URL } =
    ENV;
Vben authored
37
38
39
40
41
42
43
  return {
    VITE_GLOB_APP_TITLE,
    VITE_GLOB_API_URL,
    VITE_GLOB_API_URL_PREFIX,
    VITE_GLOB_UPLOAD_URL,
  };
Vben authored
44
45
}
陈文彬 authored
46
/**
47
 * @description: Development mode
陈文彬 authored
48
49
50
51
 */
export const devMode = 'development';

/**
vben authored
52
 * @description: Production mode
陈文彬 authored
53
54
55
56
 */
export const prodMode = 'production';

/**
vben authored
57
 * @description: Get environment variables
陈文彬 authored
58
59
60
 * @returns:
 * @example:
 */
61
62
63
export function getEnv(): string {
  return import.meta.env.MODE;
}
陈文彬 authored
64
65

/**
vben authored
66
 * @description: Is it a development mode
陈文彬 authored
67
68
69
 * @returns:
 * @example:
 */
70
71
72
export function isDevMode(): boolean {
  return import.meta.env.DEV;
}
陈文彬 authored
73
74

/**
vben authored
75
 * @description: Is it a production mode
陈文彬 authored
76
77
78
 * @returns:
 * @example:
 */
79
80
81
export function isProdMode(): boolean {
  return import.meta.env.PROD;
}