ES2020 - Access global scope with globalThis across different environments
In browser, the
window is the global object, in NodeJS it is
global while for web workers it is
self. Last but not least, only
this is available in a shell like V8's
This forced us to run some custom logic to spot the global scope:
const theGlobalScopeObject = (typeof global !== "undefined") ? global : (typeof window !== "undefined") ? window : (typeof self !== "undefined") ? self : (new Function("return this"))();
ES2020 this issue will come to an end because now we can access the global object in a unified way by calling directly
globalThis. That way, we won't have to worry about the environment our application is running on.
globalThis the snippet above can be changed to the following if we want to stay safe:
const theGlobalScopeObject = (typeof globalThis !== "undefined") ? globalThis : (typeof global !== "undefined") ? global : (typeof window !== "undefined") ? window : (typeof self !== "undefined") ? self : (new Function("return this"))();
As expected, in the browser
globalThis will return the
While in NodeJS it will return the
At the moment of this writing, globalThis is in stage 4 of the process which is considered
You can check browsers support here
If you want to access it safely, you can use a polyfill
TypeScript 3.4 introduced support for
NodeJS supports it from version 12+ and on
We can use it with the help of core-js
Get notified about latest posts and updates once a week!!
You liked it?