Skip to content

Commit

Permalink
feat: ensure global resolves in strict mode
Browse files Browse the repository at this point in the history
If CJS is bundled into ESM, then strict mode is forced.
This patch ensures that global is resolved properly in such case

Fixes #86

Thanks @mathiasbynens for hint on CSP safe global resolution
  • Loading branch information
medikoo committed Apr 30, 2019
1 parent 708202d commit c6a19d7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
18 changes: 14 additions & 4 deletions global.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
/* eslint strict: "off" */

module.exports = (function () {
return this;
}());
if (this) return this;

// Unexpected strict mode (may happen if e.g. bundled into ESM module) be nice

// Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
// In all ES5 engines global object inherits from Object.prototype
// (if you approached one that doesn't please report)
Object.defineProperty(Object.prototype, "__global__", {
get: function () { return this; },
configurable: true
});
try { return __global__; }
finally { delete Object.prototype.__global__; }
})();
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,18 @@
"root": true,
"rules": {
"no-extend-native": "off"
}
},
"overrides": [
{
"files": "global.js",
"globals": {
"__global__": true
},
"rules": {
"strict": "off"
}
}
]
},
"scripts": {
"lint": "eslint --ignore-path=.gitignore .",
Expand Down
1 change: 1 addition & 0 deletions test/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
module.exports = function (t, a) {
a.ok(t && typeof t === "object");
a(typeof t.Array, "function");
a("__global__" in Object.prototype, false);
};

0 comments on commit c6a19d7

Please sign in to comment.