Skip to content

Commit 8038073

Browse files
authored
Merge pull request webpack#3161 from einarlove/patch-1
Add option to pass object with defaults to environment plugin
2 parents adb4b70 + 45d9959 commit 8038073

1 file changed

Lines changed: 25 additions & 9 deletions

File tree

‎lib/EnvironmentPlugin.js‎

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/*
22
MIT License http://www.opensource.org/licenses/mit-license.php
3-
Author Simen Brekken @simenbrekken
3+
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
44
*/
55

66
"use strict";
@@ -9,25 +9,41 @@ const DefinePlugin = require("./DefinePlugin");
99

1010
class EnvironmentPlugin {
1111
constructor(keys) {
12-
this.keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments);
12+
if(Array.isArray(keys)) {
13+
this.keys = keys;
14+
this.defaultValues = {};
15+
} else if(keys && typeof keys === "object") {
16+
this.keys = Object.keys(keys);
17+
this.defaultValues = keys;
18+
} else {
19+
this.keys = Array.prototype.slice.call(arguments);
20+
this.defaultValues = {};
21+
}
1322
}
1423

1524
apply(compiler) {
16-
compiler.apply(new DefinePlugin(this.keys.reduce((definitions, key) => {
17-
const value = process.env[key];
25+
const definitions = this.keys.reduce((defs, key) => {
26+
const value = process.env[key] || this.defaultValues[key];
1827

1928
if(value === undefined) {
20-
compiler.plugin("this-compilation", (compilation) => {
21-
const error = new Error(key + " environment variable is undefined.");
29+
compiler.plugin("this-compilation", compilation => {
30+
const error = new Error(
31+
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
32+
"You can pass an object with default values to suppress this warning.\n" +
33+
"See https://webpack.js.org/plugins/environment-plugin for example."
34+
);
35+
2236
error.name = "EnvVariableNotDefinedError";
2337
compilation.warnings.push(error);
2438
});
2539
}
2640

27-
definitions["process.env." + key] = value ? JSON.stringify(value) : "undefined";
41+
defs[`process.env.${key}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value);
42+
43+
return defs;
44+
}, {});
2845

29-
return definitions;
30-
}, {})));
46+
compiler.apply(new DefinePlugin(definitions));
3147
}
3248
}
3349

0 commit comments

Comments
 (0)