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