Skip to content
This repository has been archived by the owner on Jun 28, 2024. It is now read-only.

SSR / pre-rendering: document is undefined #18

Open
rejhgadellaa opened this issue Jan 22, 2022 · 0 comments
Open

SSR / pre-rendering: document is undefined #18

rejhgadellaa opened this issue Jan 22, 2022 · 0 comments

Comments

@rejhgadellaa
Copy link

rejhgadellaa commented Jan 22, 2022

Description

I had some trouble using this library with preactjs/wmr, specifically when I tried to prerender the project.

At first, I didn't understand what went wrong as I had a check for typeof(document) in place before trying to do anything with the imported lifecycle library.

Then I had a look at the source code and realized page-lifecycle's export is a new Lifecycle() instance. In other words, just importing the library causes it execute code and hit a document.visibilityState statement, causing the error in environments that don't have a document object - like preactjs/wmr's prerender step.

Reproduce:

In a preactjs/wmr project, create a component and statically import the page-lifecycle library, then try to build with wmr --prerender

(Disclaimer: untested/pseudo code)

import lifecycle from 'page-lifecycle';

export default function Component() {
  if ( typeof(document) !== 'undefined) ) console.log( lifecycle.state );
  return <div />;
}
npx wmr build --prerender

Throws an error (sorry for the minified code):

ReferenceError: document is not defined
> 1 | …(((e,n,t)=>(e[n]=t,e)),{}))),yn=()=>document.visibilityState===un?un:docu…

Workaround:

Import src/Lifecycle.mjs directly and instantiate the exported class manually:

import Lifecycle from 'page-lifecycle/src/Lifecycle.mjs';

export default function Component() {
  if ( typeof(document) !== 'undefined) ) {
    const lifecycle = new Lifecycle();
    console.log( lifecycle.state );
  }
  return <div />;
}
npx wmr build --prerender
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant