webpack/lib/EnvironmentPlugin.js

70 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2015-01-07 06:02:44 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
2015-01-07 06:02:44 +08:00
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
2018-07-30 23:08:51 +08:00
const WebpackError = require("./WebpackError");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
class EnvironmentPlugin {
2024-08-06 11:08:48 +08:00
/**
2025-03-11 22:20:50 +08:00
* @param {(string | string[] | Record<string, EXPECTED_ANY>)[]} keys keys
2024-08-06 11:08:48 +08:00
*/
2017-11-08 18:32:05 +08:00
constructor(...keys) {
2018-02-25 09:00:20 +08:00
if (keys.length === 1 && Array.isArray(keys[0])) {
2024-08-28 06:37:17 +08:00
/** @type {string[]} */
2017-11-08 18:32:05 +08:00
this.keys = keys[0];
2017-01-11 16:12:55 +08:00
this.defaultValues = {};
2018-02-25 09:00:20 +08:00
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
2017-11-08 18:32:05 +08:00
this.keys = Object.keys(keys[0]);
2025-03-11 22:20:50 +08:00
this.defaultValues =
/** @type {Record<string, EXPECTED_ANY>} */
(keys[0]);
2017-01-06 22:40:28 +08:00
} else {
2024-08-06 11:08:48 +08:00
this.keys = /** @type {string[]} */ (keys);
2017-01-11 16:12:55 +08:00
this.defaultValues = {};
2015-01-07 06:02:44 +08:00
}
}
2015-01-07 06:02:44 +08:00
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
/** @type {Record<string, CodeValue>} */
const definitions = {};
for (const key of this.keys) {
2018-02-25 09:00:20 +08:00
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
2018-02-25 09:00:20 +08:00
if (value === undefined) {
compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
const error = new WebpackError(
2018-03-26 22:56:10 +08:00
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
2018-02-25 09:00:20 +08:00
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
2017-01-06 22:40:28 +08:00
);
2015-01-07 06:02:44 +08:00
error.name = "EnvVariableNotDefinedError";
compilation.errors.push(error);
});
}
2015-01-07 06:02:44 +08:00
definitions[`process.env.${key}`] =
2018-08-21 08:26:50 +08:00
value === undefined ? "undefined" : JSON.stringify(value);
}
2015-01-07 06:02:44 +08:00
new DefinePlugin(definitions).apply(compiler);
}
}
module.exports = EnvironmentPlugin;