My team and I are currently in the process of building a new Vue SSR application using Nuxt within a monorepo setup. We have organized the Nuxt app as a package, with another package serving as our component library. While we are relatively new to Typescript, we managed to set up everything smoothly.
However, we encountered an issue: the component library needs to be SSR-friendly but should not have dependencies on Nuxt itself. In order to access window properties, I prefer using
if (typeof window !== 'undefined')
over if (process.browser)
. This leads me to wonder if it is possible to utilize Typescript and Eslint to generate an error when someone attempts to access window properties without verifying if they are defined first.
// Not SSR friendly
const halfWinHeight = window.innerHeight / 2
// SSR friendly
if (typeof window !== 'undefined') {
const halfWinHeight = window.innerHeight / 2
}
I am aware that Typescript will throw an error if a union type like the following is utilized:
declare const window: {} | undefined
This would result in the desired error message Object is possibly 'undefined'
.
https://i.sstatic.net/vSaLc.png
In essence, my goal is to avoid specifying all potential window
and document
properties individually. Instead, I am exploring the option of utilizing a lib such as DOM
, but one that could potentially be undefined. The challenge lies in the fact that we only ascertain whether window is defined or not during runtime, so how can I provide it with a value to inform Typescript at compile time?
I am attempting to tackle this issue with Typescript, although there may be alternative approaches to consider. Any assistance on this matter would be immensely appreciated.