EnvironmentPlugin.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 WebpackError = require("./WebpackError");
  8. /** @typedef {import("./Compiler")} Compiler */
  9. /** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
  10. class EnvironmentPlugin {
  11. constructor(...keys) {
  12. if (keys.length === 1 && Array.isArray(keys[0])) {
  13. this.keys = keys[0];
  14. this.defaultValues = {};
  15. } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
  16. this.keys = Object.keys(keys[0]);
  17. this.defaultValues = keys[0];
  18. } else {
  19. this.keys = keys;
  20. this.defaultValues = {};
  21. }
  22. }
  23. /**
  24. * Apply the plugin
  25. * @param {Compiler} compiler the compiler instance
  26. * @returns {void}
  27. */
  28. apply(compiler) {
  29. /** @type {Record<string, CodeValue>} */
  30. const definitions = {};
  31. for (const key of this.keys) {
  32. const value =
  33. process.env[key] !== undefined
  34. ? process.env[key]
  35. : this.defaultValues[key];
  36. if (value === undefined) {
  37. compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
  38. const error = new WebpackError(
  39. `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
  40. "You can pass an object with default values to suppress this warning.\n" +
  41. "See https://webpack.js.org/plugins/environment-plugin for example."
  42. );
  43. error.name = "EnvVariableNotDefinedError";
  44. compilation.errors.push(error);
  45. });
  46. }
  47. definitions[`process.env.${key}`] =
  48. value === undefined ? "undefined" : JSON.stringify(value);
  49. }
  50. new DefinePlugin(definitions).apply(compiler);
  51. }
  52. }
  53. module.exports = EnvironmentPlugin;