utils.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import fs from 'fs';
  2. import path from 'path';
  3. import dotenv from 'dotenv';
  4. // Read all environment variable configuration files to process.env
  5. export function wrapperEnv(envConf: Recordable): ViteEnv {
  6. const ret: any = {};
  7. for (const envName of Object.keys(envConf)) {
  8. let realName = envConf[envName].replace(/\\n/g, '\n');
  9. realName = realName === 'true' ? true : realName === 'false' ? false : realName;
  10. if (envName === 'VITE_PROXY' && realName) {
  11. try {
  12. realName = JSON.parse(realName.replace(/'/g, '"'));
  13. } catch (error) {
  14. realName = '';
  15. }
  16. }
  17. ret[envName] = realName;
  18. // if (typeof realName === 'string') {
  19. // process.env[envName] = realName;
  20. // } else if (typeof realName === 'object') {
  21. // process.env[envName] = JSON.stringify(realName);
  22. // }
  23. }
  24. return ret;
  25. }
  26. /**
  27. * 获取当前环境下生效的配置文件名
  28. */
  29. function getConfFiles() {
  30. const script = process.env.npm_lifecycle_script;
  31. const reg = new RegExp('--mode ([a-z_\\d]+)');
  32. const result = reg.exec(script as string) as any;
  33. if (result) {
  34. const mode = result[1] as string;
  35. return ['.env', `.env.${mode}`];
  36. }
  37. return ['.env', '.env.production'];
  38. }
  39. /**
  40. * Get the environment variables starting with the specified prefix
  41. * @param match prefix
  42. * @param confFiles ext
  43. */
  44. export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
  45. let envConfig = {};
  46. confFiles.forEach((item) => {
  47. try {
  48. const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
  49. envConfig = { ...envConfig, ...env };
  50. } catch (e) {
  51. console.error(`Error in parsing ${item}`, e);
  52. }
  53. });
  54. const reg = new RegExp(`^(${match})`);
  55. Object.keys(envConfig).forEach((key) => {
  56. if (!reg.test(key)) {
  57. Reflect.deleteProperty(envConfig, key);
  58. }
  59. });
  60. return envConfig;
  61. }
  62. /**
  63. * Get user root directory
  64. * @param dir file path
  65. */
  66. export function getRootPath(...dir: string[]) {
  67. return path.resolve(process.cwd(), ...dir);
  68. }