2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
8 const DefinePlugin = require("./DefinePlugin");
9 const WebpackError = require("./WebpackError");
11 /** @typedef {import("./Compiler")} Compiler */
12 /** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
14 class EnvironmentPlugin {
15 constructor(...keys) {
16 if (keys.length === 1 && Array.isArray(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 = keys[0];
24 this.defaultValues = {};
30 * @param {Compiler} compiler the compiler instance
34 /** @type {Record<string, CodeValue>} */
35 const definitions = {};
36 for (const key of this.keys) {
38 process.env[key] !== undefined
40 : 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."
50 error.name = "EnvVariableNotDefinedError";
51 compilation.errors.push(error);
55 definitions[`process.env.${key}`] =
56 value === undefined ? "undefined" : JSON.stringify(value);
59 new DefinePlugin(definitions).apply(compiler);
63 module.exports = EnvironmentPlugin;