Blame view

build/utils.ts 2.29 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;
27
    if (envName === 'VITE_PROXY' && realName) {
28
      try {
29
        realName = JSON.parse(realName.replace(/'/g, '"'));
30
31
32
      } catch (error) {
        realName = '';
      }
33
    }
陈文彬 authored
34
    ret[envName] = realName;
35
36
37
38
39
    // if (typeof realName === 'string') {
    //   process.env[envName] = realName;
    // } else if (typeof realName === 'object') {
    //   process.env[envName] = JSON.stringify(realName);
    // }
陈文彬 authored
40
41
42
  }
  return ret;
}
43
vben authored
44
/**
45
46
47
48
 * 获取当前环境下生效的配置文件名
 */
function getConfFiles() {
  const script = process.env.npm_lifecycle_script;
49
  const reg = new RegExp('--mode ([a-z_\\d]+)');
50
51
52
53
54
55
56
57
58
  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
59
60
61
62
 * Get the environment variables starting with the specified prefix
 * @param match prefix
 * @param confFiles ext
 */
63
export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
64
65
66
67
68
  let envConfig = {};
  confFiles.forEach((item) => {
    try {
      const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
      envConfig = { ...envConfig, ...env };
69
70
71
    } catch (e) {
      console.error(`Error in parsing ${item}`, e);
    }
72
  });
73
  const reg = new RegExp(`^(${match})`);
74
75
76
77
78
79
80
81
  Object.keys(envConfig).forEach((key) => {
    if (!reg.test(key)) {
      Reflect.deleteProperty(envConfig, key);
    }
  });
  return envConfig;
}
vben authored
82
83
84
85
/**
 * Get user root directory
 * @param dir file path
 */
Vben authored
86
export function getRootPath(...dir: string[]) {
87
88
  return path.resolve(process.cwd(), ...dir);
}