env.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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))
  18. return;
  19. const ENV = process.env.NODE_ENV;
  20. const common = config({path: commonEnv}).parsed;
  21. const value = config({path: envs[ENV]}).parsed;
  22. const temp = {};
  23. common && Object.assign(temp, common);
  24. value && Object.assign(temp, value);
  25. for (const [key, value] of Object.entries(temp)) {
  26. !key.includes(prefix)
  27. ? (env[key] = JSON.stringify(value))
  28. : (swtEnv[key.replace(prefix, '')] = value);
  29. }
  30. }
  31. function getSWTEnv() {
  32. initEnv();
  33. return swtEnv;
  34. }
  35. function getEnv() {
  36. initEnv();
  37. return env;
  38. }
  39. module.exports = {
  40. getEnv,
  41. getSWTEnv,
  42. };