Skip to content

Commit 3d3796c

Browse files
marnixkjaylinski
authored andcommitted
Make library compatible with workers
When using Handlebars in a Cloudflare Worker, an environment in which the `window` and `global` objects both don't exist, an error is thrown about `window` being undefined. According to the ECMA specification, only `self` is available in a worker. Since we support old runtimes in our 4.x branch, we can't use `globalThis` but have to use a polyfill.
1 parent 075b354 commit 3d3796c

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

lib/handlebars/no-conflict.js

+15-5
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
1-
/* global global, window */
1+
/* global globalThis */
22
export default function(Handlebars) {
33
/* istanbul ignore next */
4-
let root = typeof global !== 'undefined' ? global : window,
5-
$Handlebars = root.Handlebars;
4+
// https://mathiasbynens.be/notes/globalthis
5+
(function() {
6+
if (typeof globalThis === 'object') return;
7+
Object.prototype.__defineGetter__('__magic__', function() {
8+
return this;
9+
});
10+
__magic__.globalThis = __magic__; // eslint-disable-line no-undef
11+
delete Object.prototype.__magic__;
12+
})();
13+
14+
const $Handlebars = globalThis.Handlebars;
15+
616
/* istanbul ignore next */
717
Handlebars.noConflict = function() {
8-
if (root.Handlebars === Handlebars) {
9-
root.Handlebars = $Handlebars;
18+
if (globalThis.Handlebars === Handlebars) {
19+
globalThis.Handlebars = $Handlebars;
1020
}
1121
return Handlebars;
1222
};

0 commit comments

Comments
 (0)