EnvironmentPlugin.js 1.9 KB

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