`window` / `globalThis` handling
Type of Change
- New Feature Request
Summary
Coming out of https://github.com/ProjectEvergreen/greenwood/pull/992, saw instances where code that was getting SSR'd in WCC was failing due to window not being defined, like in the Greenwood router.
ReferenceError [Error]: window is not defined
at file:///Users/owenbuckley/Workspace/project-evergreen/repos/greenwood/packages/cli/src/lib/router.js:45:1
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async initializeCustomElement (file:///Users/owenbuckley/Workspace/project-evergreen/repos/greenwood/node_modules/wc-compiler/src/wcc.js:139:8)
at async renderFromHTML (file:///Users/owenbuckley/Workspace/project-evergreen/repos/greenwood/node_modules/wc-compiler/src/wcc.js:193:5)
at async executeRouteModule (file:///Users/owenbuckley/Workspace/project-evergreen/repos/greenwood/packages/cli/src/lib/ssr-route-worker.js:17:22)
at async MessagePort.<anonymous> (file:///Users/owenbuckley/Workspace/project-evergreen/repos/greenwood/packages/cli/src/lib/ssr-route-worker.js:47:3)
error Command failed with exit code 1.
Details
We currently use globalThis in the dom shim, but don't test for it specifically, or call it out clearly that it should be the convention, so let's do that here. We probably shouldn't expose window specifically, but rather encourage anyone writing isomorphic code to use globalThis instead.
The
globalThisproperty provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the this value isglobalThis.