getEnv.ts 1017 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import path from 'path';
  2. import fs from 'fs';
  3. import dotenv from 'dotenv';
  4. interface EnvConfig {
  5. [key: string]: string;
  6. }
  7. //读取env 文件配置
  8. const loadEnv = () => {
  9. const envRoot = path.resolve(process.cwd());
  10. const mode = getMode();
  11. // 加载默认环境变量
  12. const envFilePath = path.resolve(envRoot, `./env`);
  13. if (fs.existsSync(envFilePath)) {
  14. dotenv.config({ path: envFilePath });
  15. }
  16. //加载特定环境变量
  17. const envModeFilePath = path.resolve(envRoot, `./env/${mode}`);
  18. if (fs.existsSync(envModeFilePath)) {
  19. dotenv.config({ path: envModeFilePath });
  20. }
  21. };
  22. //获取指令参数
  23. const getMode = () => {
  24. const args = process.argv
  25. .find((item) => item.startsWith('--mode'))
  26. ?.split('=')[1];
  27. if (args) return args;
  28. const mode = process.env.NODE_ENV;
  29. return mode || 'development';
  30. };
  31. const isDev = () => {
  32. return getMode() === 'development';
  33. };
  34. const isProd = () => {
  35. return getMode() === 'production';
  36. };
  37. export { loadEnv, getMode, isDev, isProd };