better global support, even in strict mode

This commit is contained in:
Tobias Koppers 2016-05-06 11:36:36 +02:00
parent e83e9b8c23
commit 2ff9a247e2
4 changed files with 31 additions and 2 deletions

19
buildin/global.js Normal file
View File

@ -0,0 +1,19 @@
var g;
// This works in non-strict mode
g = (function() { return this; })();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;

View File

@ -29,8 +29,7 @@ NodeSourcePlugin.prototype.apply = function(compiler) {
} }
if(this.options.global) { if(this.options.global) {
compiler.parser.plugin("expression global", function() { compiler.parser.plugin("expression global", function() {
this.state.module.addVariable("global", "(function() { return this; }())"); return ModuleParserHelpers.addParsedVariable(this, "global", "require(" + JSON.stringify(require.resolve("../../buildin/global.js")) + ")");
return true;
}); });
} }
if(this.options.console) { if(this.options.console) {

View File

@ -0,0 +1,8 @@
"use strict";
require("should");
it("should be able to use global in strict mode", function() {
(typeof global).should.be.eql("object");
(global === null).should.be.eql(false)
});

View File

@ -0,0 +1,3 @@
module.exports = {
target: "web"
};