UNPKG

1.74 kBJavaScriptView Raw
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
8const DefinePlugin = require("./DefinePlugin");
9const WebpackError = require("./WebpackError");
10
11/** @typedef {import("./Compiler")} Compiler */
12/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
13
14class EnvironmentPlugin {
15 constructor(...keys) {
16 if (keys.length === 1 && Array.isArray(keys[0])) {
17 this.keys = 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];
22 } else {
23 this.keys = keys;
24 this.defaultValues = {};
25 }
26 }
27
28 /**
29 * Apply the plugin
30 * @param {Compiler} compiler the compiler instance
31 * @returns {void}
32 */
33 apply(compiler) {
34 /** @type {Record<string, CodeValue>} */
35 const definitions = {};
36 for (const key of this.keys) {
37 const value =
38 process.env[key] !== undefined
39 ? process.env[key]
40 : this.defaultValues[key];
41
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."
48 );
49
50 error.name = "EnvVariableNotDefinedError";
51 compilation.errors.push(error);
52 });
53 }
54
55 definitions[`process.env.${key}`] =
56 value === undefined ? "undefined" : JSON.stringify(value);
57 }
58
59 new DefinePlugin(definitions).apply(compiler);
60 }
61}
62
63module.exports = EnvironmentPlugin;