EnvironmentPlugin.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. const needsEnvVarFix = ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 &&
  8. process.platform === "win32";
  9. class EnvironmentPlugin {
  10. constructor(keys) {
  11. if(Array.isArray(keys)) {
  12. this.keys = keys;
  13. this.defaultValues = {};
  14. } else if(keys && typeof keys === "object") {
  15. this.keys = Object.keys(keys);
  16. this.defaultValues = keys;
  17. } else {
  18. this.keys = Array.prototype.slice.call(arguments);
  19. this.defaultValues = {};
  20. }
  21. }
  22. apply(compiler) {
  23. const definitions = this.keys.reduce((defs, key) => {
  24. // TODO remove once the fix has made its way into Node 8.
  25. // Work around https://github.com/nodejs/node/pull/18463,
  26. // affecting Node 8 & 9 by performing an OS-level
  27. // operation that always succeeds before reading
  28. // environment variables:
  29. if(needsEnvVarFix) require("os").cpus();
  30. const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key];
  31. if(value === undefined) {
  32. compiler.plugin("this-compilation", compilation => {
  33. const error = new Error(
  34. `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
  35. "You can pass an object with default values to suppress this warning.\n" +
  36. "See https://webpack.js.org/plugins/environment-plugin for example."
  37. );
  38. error.name = "EnvVariableNotDefinedError";
  39. compilation.warnings.push(error);
  40. });
  41. }
  42. defs[`process.env.${key}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value);
  43. return defs;
  44. }, {});
  45. compiler.apply(new DefinePlugin(definitions));
  46. }
  47. }
  48. module.exports = EnvironmentPlugin;