webpack/lib/EnvironmentPlugin.js

51 lines
1.3 KiB
JavaScript
Raw 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");
class EnvironmentPlugin {
constructor(keys) {
2017-01-06 22:40:28 +08:00
this.defaultValues = {};
if(Array.isArray(keys)) {
this.keys = keys;
} else if(keys && typeof keys === "object") {
this.keys = Object.keys(keys);
this.defaultValues = keys;
} else {
this.keys = Array.prototype.slice.call(arguments);
2015-01-07 06:02:44 +08:00
}
}
2015-01-07 06:02:44 +08:00
apply(compiler) {
2017-01-06 22:40:28 +08:00
const definitions = this.keys.reduce(function(defs, key) {
const value = process.env[key] || this.defaultValues[key];
if(value === undefined) {
2017-01-06 22:40:28 +08:00
compiler.plugin("this-compilation", function(compilation) {
const error = new Error(
2017-01-10 04:48:26 +08:00
"EnvironmentPlugin - " + key + " environment variable is undefined. \n\n" +
"You can pass an object with default values to suppress this warning. \n" +
"See http://webpack.github.io/docs/list-of-plugins.html#environmentplugin for example."
2017-01-06 22:40:28 +08:00
);
2015-01-07 06:02:44 +08:00
error.name = "EnvVariableNotDefinedError";
compilation.warnings.push(error);
});
}
2015-01-07 06:02:44 +08:00
2017-01-10 04:48:26 +08:00
defs["process.env." + key] = value === undefined ? "undefined" : JSON.stringify(value);
2017-01-06 22:40:28 +08:00
return defs;
}.bind(this), {});
2015-01-07 06:02:44 +08:00
2017-01-06 22:40:28 +08:00
compiler.apply(new DefinePlugin(definitions));
}
}
module.exports = EnvironmentPlugin;