EnvironmentPlugin.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
  4. */
  5. "use strict";
  6. const DefinePlugin = require("./DefinePlugin");
  7. class EnvironmentPlugin {
  8. constructor(keys) {
  9. if(Array.isArray(keys)) {
  10. this.keys = keys;
  11. this.defaultValues = {};
  12. } else if(keys && typeof keys === "object") {
  13. this.keys = Object.keys(keys);
  14. this.defaultValues = keys;
  15. } else {
  16. this.keys = Array.prototype.slice.call(arguments);
  17. this.defaultValues = {};
  18. }
  19. }
  20. apply(compiler) {
  21. const definitions = this.keys.reduce((defs, key) => {
  22. const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key];
  23. if(value === undefined) {
  24. compiler.plugin("this-compilation", compilation => {
  25. const error = new Error(
  26. `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
  27. "You can pass an object with default values to suppress this warning.\n" +
  28. "See https://webpack.js.org/plugins/environment-plugin for example."
  29. );
  30. error.name = "EnvVariableNotDefinedError";
  31. compilation.warnings.push(error);
  32. });
  33. }
  34. defs[`process.env.${key}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value);
  35. return defs;
  36. }, {});
  37. compiler.apply(new DefinePlugin(definitions));
  38. }
  39. }
  40. module.exports = EnvironmentPlugin;