utils.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import * as dotenv from "dotenv";
  2. export interface ViteEnv {
  3. VITE_PORT: number;
  4. VITE_OPEN: boolean;
  5. VITE_USE_MOCK: boolean;
  6. VITE_PUBLIC_PATH: string;
  7. VITE_PROXY: [string, string][];
  8. }
  9. export function loadEnv(): ViteEnv {
  10. const env = process.env.NODE_ENV;
  11. const ret: any = {};
  12. // eslint-disable-next-line no-sparse-arrays
  13. const envList = [`.env.${env}.local`, `.env.${env}`, ".env.local", ".env", ,];
  14. envList.forEach(e => {
  15. dotenv.config({
  16. path: e
  17. });
  18. });
  19. for (const envName of Object.keys(process.env)) {
  20. let realName = (process.env as any)[envName].replace(/\\n/g, "\n");
  21. realName =
  22. realName === "true" ? true : realName === "false" ? false : realName;
  23. if (envName === "VITE_PORT") {
  24. realName = Number(realName);
  25. }
  26. if (envName === "VITE_OPEN") {
  27. realName = Boolean(realName);
  28. }
  29. if (envName === "VITE_PROXY") {
  30. try {
  31. realName = JSON.parse(realName);
  32. // eslint-disable-next-line no-empty
  33. } catch (error) {}
  34. }
  35. ret[envName] = realName;
  36. process.env[envName] = realName;
  37. }
  38. return ret;
  39. }