Linter · Rules
unicorn/prefer-global-this
Require globalThis instead of window, self and global
A worker has no window, a browser has no global, and Node.js has no self. Code that names one of them throws a ReferenceError where it doesn't exist. globalThis is the same object and exists everywhere.
Properties that only make sense on one of them are allowed, such as window.innerWidth, window.addEventListener("resize", ...) and self.postMessage(). Computed access such as window[name] is allowed too, and so is your own variable with one of these names.
Configure
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-global-this" = "error" # or "warn"
Examples
Reported:
global.cache = new Map();
window.setTimeout(refresh, 1000);
if (typeof window !== "undefined") {
start();
}
Not reported:
globalThis.cache = new Map();
globalThis.setTimeout(refresh, 1000);
if (typeof globalThis.window !== "undefined") {
start();
}
const width = window.innerWidth;
window.addEventListener("resize", layout);
self.postMessage({ done: true });
const handler = window[name];
An event that isn't specific to the window is reported:
window.addEventListener("click", close);