Skip to content

use of window libs or localStorage #43

Answered by frandiox
calebeaires asked this question in Q&A
Discussion options

You must be logged in to vote

@calebeaires Hi! If you have access to the code, you can do:

if (!import.meta.env.SSR) {
  window.anything

  myFunctionThatCallsWindow()
}

If it's a component that checks window during rendering, there's a ClientOnly component wrapper to make it run only in the browser:

import { ClientOnly } from 'vitedge'

...
<ClientOnly>
 <MyComponentThatCallsWindow />
</ClientOnly>

If it's a library that calls window on import, you can use dynamic imports like this:

let library
if (!import.meta.env.SSR) {
  lib = await import('my-lib')
}

If dynamic imports are an issue for any reason, add vite-plugin-iso-import and use normal imports:

import lib from 'my-lib?client'

if (!import.meta.env.SSR) {
  // …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@calebeaires
Comment options

@frandiox
Comment options

Answer selected by frandiox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants