EnvironmentPlugin.js 2.2 KB

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