EnvironmentPlugin.js 1.9 KB

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