EnvironmentPlugin.js 1.9 KB

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