env.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import {config} from 'dotenv';
  2. import {resolve} from 'path';
  3. import {appPath} from './paths.ts';
  4. export type SWTEnv = {
  5. readonly HOST: string;
  6. readonly ENABLE_SOURCE_MAP: 'true' | undefined;
  7. readonly ENABLE_SWC: 'true' | undefined;
  8. readonly MAX_CHUNK_SIZE: 'true' | undefined;
  9. };
  10. const commonEnv = resolve(appPath, '.env');
  11. const prefix = 'SWT_';
  12. const envs = {
  13. test: resolve(appPath, '.env.test'),
  14. development: resolve(appPath, '.env.dev'),
  15. production: resolve(appPath, '.env.pro'),
  16. };
  17. const env: Record<string, string> = {};
  18. const swtEnv: Record<string, string> = {};
  19. function objectIsEmpty(obj: Record<string, string>) {
  20. return Object.getOwnPropertyNames(obj).length === 0;
  21. }
  22. function initEnv() {
  23. if (!objectIsEmpty(env) && !objectIsEmpty(swtEnv)) {
  24. return;
  25. }
  26. const ENV = process.env.NODE_ENV;
  27. const common = config({path: commonEnv}).parsed;
  28. const value = config({path: envs[ENV]}).parsed;
  29. const temp: Record<string, string> = {};
  30. common && Object.assign(temp, common);
  31. value && Object.assign(temp, value);
  32. for (const [key, value] of Object.entries(temp)) {
  33. !key.includes(prefix)
  34. ? (env[key] = JSON.stringify(value))
  35. : (swtEnv[key.replace(prefix, '')] = value);
  36. }
  37. }
  38. export function getSWTEnv() {
  39. initEnv();
  40. return swtEnv;
  41. }
  42. export function getEnv() {
  43. initEnv();
  44. return env;
  45. }