您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

EnvironmentPlugin.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /** @typedef {import("./Compiler")} Compiler */
  7. const WebpackError = require("./WebpackError");
  8. const DefinePlugin = require("./DefinePlugin");
  9. const needsEnvVarFix =
  10. ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 &&
  11. process.platform === "win32";
  12. class EnvironmentPlugin {
  13. constructor(...keys) {
  14. if (keys.length === 1 && Array.isArray(keys[0])) {
  15. this.keys = keys[0];
  16. this.defaultValues = {};
  17. } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
  18. this.keys = Object.keys(keys[0]);
  19. this.defaultValues = keys[0];
  20. } else {
  21. this.keys = keys;
  22. this.defaultValues = {};
  23. }
  24. }
  25. /**
  26. * @param {Compiler} compiler webpack compiler instance
  27. * @returns {void}
  28. */
  29. apply(compiler) {
  30. const definitions = this.keys.reduce((defs, key) => {
  31. // TODO remove once the fix has made its way into Node 8.
  32. // Work around https://github.com/nodejs/node/pull/18463,
  33. // affecting Node 8 & 9 by performing an OS-level
  34. // operation that always succeeds before reading
  35. // environment variables:
  36. if (needsEnvVarFix) require("os").cpus();
  37. const value =
  38. process.env[key] !== undefined
  39. ? process.env[key]
  40. : this.defaultValues[key];
  41. if (value === undefined) {
  42. compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
  43. const error = new WebpackError(
  44. `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
  45. "You can pass an object with default values to suppress this warning.\n" +
  46. "See https://webpack.js.org/plugins/environment-plugin for example."
  47. );
  48. error.name = "EnvVariableNotDefinedError";
  49. compilation.warnings.push(error);
  50. });
  51. }
  52. defs[`process.env.${key}`] =
  53. value === undefined ? "undefined" : JSON.stringify(value);
  54. return defs;
  55. }, {});
  56. new DefinePlugin(definitions).apply(compiler);
  57. }
  58. }
  59. module.exports = EnvironmentPlugin;