How to optionally use `window` variable in Node/Browser module?

151 Views Asked by At

Running a script via NodeJS which imports from a library is failing because the library references the window variable. Even though in the library, it looks like this:

{
  baseUrl: (typeof window !== undefined ? window.location.origin : '') + "/blah",
}

This line still results in the following error when running the script via NodeJS:

ReferenceError: window is not defined

I thought it was enough to add the typeof window !== undefined check but clearly that is not the case. What am I missing here? (FWIW the imported module is a UMD module.)

1

There are 1 best solutions below

1
On BEST ANSWER

typeof gives you a string so you need to be comparing to "undefined", not undefined. Change your code to this:

{
  baseUrl: (typeof window !== "undefined" ? window.location.origin : '') + "/blah",
}