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