env.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { join } from 'node:path';
  2. import dotenv from 'dotenv';
  3. import { readFile } from 'fs-extra';
  4. /**
  5. * 获取当前环境下生效的配置文件名
  6. */
  7. function getConfFiles() {
  8. const script = process.env.npm_lifecycle_script as string;
  9. const reg = new RegExp('--mode ([a-z_\\d]+)');
  10. const result = reg.exec(script);
  11. if (result) {
  12. const mode = result[1];
  13. return ['.env', `.env.${mode}`];
  14. }
  15. return ['.env', '.env.production'];
  16. }
  17. /**
  18. * Get the environment variables starting with the specified prefix
  19. * @param match prefix
  20. * @param confFiles ext
  21. */
  22. export async function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
  23. let envConfig = {};
  24. for (const confFile of confFiles) {
  25. try {
  26. const envPath = await readFile(join(process.cwd(), confFile), { encoding: 'utf8' });
  27. const env = dotenv.parse(envPath);
  28. envConfig = { ...envConfig, ...env };
  29. } catch (e) {
  30. console.error(`Error in parsing ${confFile}`, e);
  31. }
  32. }
  33. const reg = new RegExp(`^(${match})`);
  34. Object.keys(envConfig).forEach((key) => {
  35. if (!reg.test(key)) {
  36. Reflect.deleteProperty(envConfig, key);
  37. }
  38. });
  39. return envConfig;
  40. }