utils.ts 2.3 KB
Newer Older
陈文彬 已提交
1
import fs from 'fs';
2
import path from 'path';
陈文彬 已提交
3
import dotenv from 'dotenv';
4

V
vben 已提交
5
export function isDevFn(mode: string): boolean {
6
  return mode === 'development';
陈文彬 已提交
7 8
}

V
vben 已提交
9
export function isProdFn(mode: string): boolean {
10
  return mode === 'production';
陈文彬 已提交
11 12
}

V
vben 已提交
13 14 15
/**
 * Whether to generate package preview
 */
陈文彬 已提交
16 17 18
export function isReportMode(): boolean {
  return process.env.REPORT === 'true';
}
V
vben 已提交
19 20

// Read all environment variable configuration files to process.env
V
Vben 已提交
21
export function wrapperEnv(envConf: Recordable): ViteEnv {
陈文彬 已提交
22 23
  const ret: any = {};

24 25
  for (const envName of Object.keys(envConf)) {
    let realName = envConf[envName].replace(/\\n/g, '\n');
B
bin 已提交
26
    realName = realName === 'true' ? true : realName === 'false' ? false : realName;
V
Vben 已提交
27

B
bin 已提交
28 29 30 31 32 33 34 35
    if (envName === 'VITE_PORT') {
      realName = Number(realName);
    }
    if (envName === 'VITE_PROXY') {
      try {
        realName = JSON.parse(realName);
      } catch (error) {}
    }
陈文彬 已提交
36
    ret[envName] = realName;
37 38 39 40 41
    if (typeof realName === 'string') {
      process.env[envName] = realName;
    } else if (typeof realName === 'object') {
      process.env[envName] = JSON.stringify(realName);
    }
陈文彬 已提交
42 43 44
  }
  return ret;
}
45

46 47 48 49 50
/**
 * 获取当前环境下生效的配置文件名
 */
function getConfFiles() {
  const script = process.env.npm_lifecycle_script;
51
  const reg = new RegExp('--mode ([a-z]+)');
52 53 54 55 56 57 58 59
  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'];
}

V
vben 已提交
60 61 62 63 64
/**
 * Get the environment variables starting with the specified prefix
 * @param match prefix
 * @param confFiles ext
 */
65
export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
66 67 68 69 70
  let envConfig = {};
  confFiles.forEach((item) => {
    try {
      const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
      envConfig = { ...envConfig, ...env };
71 72 73
    } catch (e) {
      console.error(`Error in parsing ${item}`, e);
    }
74
  });
75
  const reg = new RegExp(`^(${match})`);
76 77 78 79 80 81 82 83
  Object.keys(envConfig).forEach((key) => {
    if (!reg.test(key)) {
      Reflect.deleteProperty(envConfig, key);
    }
  });
  return envConfig;
}

V
vben 已提交
84 85 86 87
/**
 * Get user root directory
 * @param dir file path
 */
V
Vben 已提交
88
export function getRootPath(...dir: string[]) {
89 90
  return path.resolve(process.cwd(), ...dir);
}