env.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { join } from 'node:path';
  2. import { fs } from '@vben/node-utils';
  3. import dotenv from 'dotenv';
  4. /**
  5. * 获取当前环境下生效的配置文件名
  6. */
  7. function getConfFiles() {
  8. const script = process.env.npm_lifecycle_script as string;
  9. const reg = /--mode ([\d_a-z]+)/;
  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(
  23. match = 'VITE_GLOB_',
  24. confFiles = getConfFiles(),
  25. ) {
  26. let envConfig = {};
  27. for (const confFile of confFiles) {
  28. try {
  29. const envPath = await fs.readFile(join(process.cwd(), confFile), {
  30. encoding: 'utf8',
  31. });
  32. const env = dotenv.parse(envPath);
  33. envConfig = { ...envConfig, ...env };
  34. } catch (error) {
  35. console.error(`Error while parsing ${confFile}`, error);
  36. }
  37. }
  38. const reg = new RegExp(`^(${match})`);
  39. Object.keys(envConfig).forEach((key) => {
  40. if (!reg.test(key)) {
  41. Reflect.deleteProperty(envConfig, key);
  42. }
  43. });
  44. return envConfig;
  45. }