Blame view

build/utils.ts 2.36 KB
陈文彬 authored
1
import fs from 'fs';
2
import path from 'path';
陈文彬 authored
3
import dotenv from 'dotenv';
4
vben authored
5
export function isDevFn(mode: string): boolean {
6
  return mode === 'development';
陈文彬 authored
7
8
}
vben authored
9
export function isProdFn(mode: string): boolean {
10
  return mode === 'production';
陈文彬 authored
11
12
}
vben authored
13
14
15
/**
 * Whether to generate package preview
 */
陈文彬 authored
16
17
18
export function isReportMode(): boolean {
  return process.env.REPORT === 'true';
}
vben authored
19
20

// Read all environment variable configuration files to process.env
Vben authored
21
export function wrapperEnv(envConf: Recordable): ViteEnv {
陈文彬 authored
22
23
  const ret: any = {};
24
25
  for (const envName of Object.keys(envConf)) {
    let realName = envConf[envName].replace(/\\n/g, '\n');
26
    realName = realName === 'true' ? true : realName === 'false' ? false : realName;
Vben authored
27
28
29
30
    if (envName === 'VITE_PORT') {
      realName = Number(realName);
    }
31
    if (envName === 'VITE_PROXY' && realName) {
32
      try {
33
        realName = JSON.parse(realName.replace(/'/g, '"'));
34
35
36
      } catch (error) {
        realName = '';
      }
37
    }
陈文彬 authored
38
    ret[envName] = realName;
39
40
41
42
43
    if (typeof realName === 'string') {
      process.env[envName] = realName;
    } else if (typeof realName === 'object') {
      process.env[envName] = JSON.stringify(realName);
    }
陈文彬 authored
44
45
46
  }
  return ret;
}
47
vben authored
48
/**
49
50
51
52
 * 获取当前环境下生效的配置文件名
 */
function getConfFiles() {
  const script = process.env.npm_lifecycle_script;
53
  const reg = new RegExp('--mode ([a-z_\\d]+)');
54
55
56
57
58
59
60
61
62
  const result = reg.exec(script as string) as any;
  if (result) {
    const mode = result[1] as string;
    return ['.env', `.env.${mode}`];
  }
  return ['.env', '.env.production'];
}

/**
vben authored
63
64
65
66
 * Get the environment variables starting with the specified prefix
 * @param match prefix
 * @param confFiles ext
 */
67
export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
68
69
70
71
72
  let envConfig = {};
  confFiles.forEach((item) => {
    try {
      const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
      envConfig = { ...envConfig, ...env };
73
74
75
    } catch (e) {
      console.error(`Error in parsing ${item}`, e);
    }
76
  });
77
  const reg = new RegExp(`^(${match})`);
78
79
80
81
82
83
84
85
  Object.keys(envConfig).forEach((key) => {
    if (!reg.test(key)) {
      Reflect.deleteProperty(envConfig, key);
    }
  });
  return envConfig;
}
vben authored
86
87
88
89
/**
 * Get user root directory
 * @param dir file path
 */
Vben authored
90
export function getRootPath(...dir: string[]) {
91
92
  return path.resolve(process.cwd(), ...dir);
}