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