antfu-collective / vite-ssg

Static site generation for Vue 3 on Vite

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReferenceError: window is not defined on build

ChristosTanailidis opened this issue · comments

Hey everyone! So I've been trying to build my app but this window is not defined error keeps occurring.
I've read all issues related with this error. It seems that the oidc-client-ts library that I have installed is using the window browser object, resulting in this error.

My src/boot/auth.ts file:

import { UserManager, WebStorageStateStore } from 'oidc-client-ts'

const settings = {
  userStore: new WebStorageStateStore({ store: window.sessionStorage }),
  ...
}
...

The error message:

[vite-ssg] An internal error occurred.
[vite-ssg] Please report an issue, if none already exists: https://github.com/antfu/vite-ssg/issues
.../.vite-ssg-temp/main.mjs:424
  userStore: new WebStorageStateStore({ store: window.sessionStorage }),
                                               ^

ReferenceError: window is not defined
    at .../.vite-ssg-temp/main.mjs:424:48
    at ModuleJob.run (node:internal/modules/esm/module_job:183:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async build (...\node_modules\.pnpm\vite-ssg@0.17.10_dd02a634c6d9f894c7a4243a6abbc11a\node_modules\vite-ssg\dist\node\cli.cjs:180:87)
    at async Object.handler (...\node_modules\.pnpm\vite-ssg@0.17.10_dd02a634c6d9f894c7a4243a6abbc11a\node_modules\vite-ssg\dist\node\cli.cjs:314:3)
 ELIFECYCLE  Command failed with exit code 1.

I've tried changing it to:

import { UserManager, WebStorageStateStore } from 'oidc-client-ts'

const settings = {
  userStore: typeof window !== 'undefined' ? new WebStorageStateStore({ store: window.sessionStorage }) : undefined,
  ...
}
...

resulting in this error message:

ReferenceError: window is not defined
    at RedirectNavigator.prepare (.../oidc-client-ts@2.0.1/node_modules/oidc-client-ts/dist/esm/oidc-client-ts.js:1986:22)
    at UserManager.signinRedirect (.../oidc-client-ts@2.0.1/node_modules/oidc-client-ts/dist/esm/oidc-client-ts.js:2189:50)
    at AuthService.login (.../.vite-ssg-temp/main.mjs:437:17)
    at .../.vite-ssg-temp/main.mjs:3125:23

Any help would be appreciated :)

@ChristosTanailidis you must load src/boot/auth.ts using dynamic import

It's also happening to me, but the problem is that a package at node_modules is using window.document.body and it's crashing my netlify deploy. If somebody could help me, I appreciate it!

My main.ts file:

import { ViteSSG } from 'vite-ssg'
import generatedRoutes from 'virtual:generated-pages'
import { setupLayouts } from 'virtual:generated-layouts'
import App from './App.vue'

import '@unocss/reset/tailwind.css'
import './styles/main.css'
import 'uno.css'

const routes = setupLayouts(generatedRoutes)

// https://github.com/antfu/vite-ssg
export const createApp = ViteSSG(
  App,
  { routes, base: import.meta.env.BASE_URL },
  (ctx) => {
    // install all modules under `modules/`
    Object.values(import.meta.globEager('./modules/*.ts')).forEach(i => i.install?.(ctx))
  },
)

@ChristosTanailidis you must load src/boot/auth.ts using dynamic import

@userquin I just tried importing the file dynamically but I get the same error as before.

my main.ts:

export const createApp = ViteSSG(
  App,
  { routes, base: import.meta.env.BASE_URL },
  async(ctx) => {
    const { authService } = await import('./boot/auth')

    ...
)

the error message:

[vite-ssg] An internal error occurred.
[vite-ssg] Please report an issue, if none already exists: https://github.com/antfu/vite-ssg/issues
.../.vite-ssg-temp/main.mjs:3312
  userStore: new WebStorageStateStore({ store: window.sessionStorage }),
                                               ^

ReferenceError: window is not defined
    .../.vite-ssg-temp/main.mjs:3312:48
    at ModuleJob.run (node:internal/modules/esm/module_job:183:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async build (...\vite-ssg\dist\node\cli.cjs:180:87)
    at async Object.handler (...\vite-ssg\dist\node\cli.cjs:314:3)

@ChristosTanailidis check you are not on the server, only import that module when isClient is true

@ChristosTanailidis check you are not on the server, only import that module when isClient is true

But how do I do that when importing an npm package inside a component?

Example:

<script setup lang="ts">
import { Printd } from 'printd'
import cssUsed from '../helpers/cssUsed' 
const font = 'https://fonts.googleapis.com/css2?family=PT+Serif&display=swap'
const css_data = [cssUsed, font]
const d = new Printd()
const downloadPdf = () => {
  d.print(document.getElementById('cv-online-id'), css_data)
}
</script>

<template lang="pug">
div(class="min-w-screen-lg max-w-screen-lg mx-auto pb-20")
  Navbar
  Title
  StatsAndButtons(@downloadPdf="downloadPdf")
  Cv
</template>

<route lang="yaml">
meta:
  layout: home
</route>

In this case, when importing this Printd (which has the window.document.body) it's when starts to generate the problem.

Sorry if this is too dumb, but I've tried to solve this for days now.

@matheusgomes062 use onMounted/onBeforeMount hooks with async callback, these hooks will only be called on client side:

onMounted(async() => {
  const { authService } = await import('./boot/auth') // <== update the relative path
  ...
})

Ended up building my app with vite instead of vite-ssg cause I was in a hurry and too many errors popped up.
Will keep that in mind for future projects though, thank you for your help @userquin!