Skip to content

Commit 9fe2f6c

Browse files
committed
Merge branch 'env-plugin' of https://github.com/unfold/webpack into unfold-env-plugin
2 parents ccf6513 + 8230848 commit 9fe2f6c

5 files changed

Lines changed: 65 additions & 0 deletions

File tree

lib/EnvPlugin.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Simen Brekken @simenbrekken
4+
*/
5+
var DefinePlugin = require("./DefinePlugin");
6+
7+
function EnvPlugin(keys) {
8+
this.keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments);
9+
}
10+
module.exports = EnvPlugin;
11+
12+
EnvPlugin.prototype.apply = function(compiler) {
13+
compiler.apply(new DefinePlugin(getDefinitions(this.keys)));
14+
15+
function getDefinitions(keys) {
16+
return keys.reduce(function(definitions, key) {
17+
var value = process.env[key];
18+
19+
if (value === undefined) {
20+
compiler.plugin("compilation", function(compilation) {
21+
var error = new Error(key + " environment variable is undefined.");
22+
error.name = "EnvVariableNotDefinedError";
23+
compilation.warnings.push(error);
24+
});
25+
}
26+
27+
definitions["process.env." + key] = value ? JSON.stringify(value) : "undefined";
28+
29+
return definitions;
30+
}, {});
31+
}
32+
};

lib/webpack.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ exportPlugins(exports, ".", [
7777
"UmdMainTemplatePlugin",
7878
"NoErrorsPlugin",
7979
"NewWatchingPlugin",
80+
"EnvPlugin"
8081
]);
8182
exportPlugins(exports.optimize = {}, "./optimize", [
8283
"AggressiveMergingPlugin",
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
it("should import a single process.env var", function() {
2+
process.env.AAA.should.be.eql("aaa");
3+
});
4+
5+
it("should import multiple process.env vars", function() {
6+
process.env.BBB.should.be.eql("bbb");
7+
process.env.CCC.should.be.eql("123");
8+
});
9+
10+
it("should warn when a process.env variable is undefined", function() {
11+
(process.env.DDD === undefined).should.be.true;
12+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = [
2+
[/DDD/, /environment variable is undefined/]
3+
];
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
var EnvPlugin = require("../../../../lib/EnvPlugin");
2+
process.env.AAA = "aaa";
3+
process.env.BBB = "bbb";
4+
process.env.CCC = "123";
5+
module.exports = [{
6+
plugins: [
7+
new EnvPlugin("AAA")
8+
]
9+
}, {
10+
plugins: [
11+
new EnvPlugin("BBB", "CCC")
12+
]
13+
}, {
14+
plugins: [
15+
new EnvPlugin("DDD")
16+
]
17+
}];

0 commit comments

Comments
 (0)