index.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import fs from 'fs';
  2. import path from 'path';
  3. import appRoot from 'app-root-dir';
  4. import dotenv from 'dotenv';
  5. import dotenvExpand from 'dotenv-expand';
  6. const dotEnvBase = path.join(appRoot.get(), ".env");
  7. function getEnvironment({ nodeEnv, buildTarget } = {}) {
  8. let raw = {};
  9. const stringified = {};
  10. const webpack = { "process.env": stringified };
  11. const NODE_ENV = typeof nodeEnv === "undefined" ? process.env.NODE_ENV : nodeEnv;
  12. const BUILD_TARGET = typeof nodeEnv === "undefined" ? process.env.BUILD_TARGET : buildTarget;
  13. const dotenvFiles = [
  14. BUILD_TARGET && NODE_ENV && `${dotEnvBase}.${BUILD_TARGET}.${NODE_ENV}.local`,
  15. BUILD_TARGET && NODE_ENV && `${dotEnvBase}.${BUILD_TARGET}.${NODE_ENV}`,
  16. BUILD_TARGET && NODE_ENV !== "test" && `${dotEnvBase}.${BUILD_TARGET}.local`,
  17. BUILD_TARGET && `${dotEnvBase}.${BUILD_TARGET}`,
  18. NODE_ENV && `${dotEnvBase}.${NODE_ENV}.local`,
  19. NODE_ENV && `${dotEnvBase}.${NODE_ENV}`,
  20. NODE_ENV !== "test" && `${dotEnvBase}.local`,
  21. dotEnvBase
  22. ].filter(Boolean);
  23. dotenvFiles.forEach((dotenvFile) => {
  24. if (fs.existsSync(dotenvFile)) {
  25. const config = dotenv.config({
  26. path: dotenvFile
  27. });
  28. raw = Object.assign({}, raw, dotenvExpand.expand(config).parsed);
  29. }
  30. });
  31. Object.keys(raw).forEach((key) => {
  32. stringified[key] = JSON.stringify(raw[key]);
  33. });
  34. return { raw, stringified, webpack };
  35. }
  36. export { getEnvironment };