env.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const {config} = require('dotenv');
  2. const {resolve} = require('path');
  3. const {appPath} = require('./paths');
  4. const commonEnv = resolve(appPath, '.env');
  5. const prefix = 'SWT_';
  6. const envs = {
  7. test: resolve(appPath, '.env.test'),
  8. development: resolve(appPath, '.env.dev'),
  9. production: resolve(appPath, '.env.pro'),
  10. };
  11. const env = {};
  12. const swtEnv = {};
  13. function objectIsEmpty(obj) {
  14. return Object.getOwnPropertyNames(obj).length === 0;
  15. }
  16. function initEnv() {
  17. if (!objectIsEmpty(env) && !objectIsEmpty(swtEnv)) return;
  18. const ENV = process.env.NODE_ENV;
  19. const common = config({path: commonEnv}).parsed;
  20. const value = config({path: envs[ENV]}).parsed;
  21. const temp = {};
  22. common && Object.assign(temp, common);
  23. value && Object.assign(temp, value);
  24. for (const [key, value] of Object.entries(temp))
  25. !key.includes(prefix)
  26. ? (env[key] = JSON.stringify(value))
  27. : (swtEnv[key.replace(prefix, '')] = value);
  28. }
  29. function getSWTEnv() {
  30. initEnv();
  31. return swtEnv;
  32. }
  33. function getEnv() {
  34. initEnv();
  35. return env;
  36. }
  37. module.exports = {
  38. getEnv,
  39. getSWTEnv,
  40. };