React-static: Builds fail for components requiring `window`

Created on 10 Oct 2017  路  4Comments  路  Source: react-static/react-static

Hi there!

Really great work on this, very nice alternative to Next + Gatsby and very slick. I've been getting errors on my build, I have 2 components that need the browsers window object and they crash the build process, I've tried a few different thinks like ErrorBoundary etc. My project runs just fine in the dev environment (minus my font but ill get to that later).

Here is the error: ReferenceError: window is not defined

Here is the Repo

Anyway, thanks for this killer project, deff gonna use this for some more things in the future.

Most helpful comment

Since react-static builds static versions of your site, most times you'll need to make sure the window object is available (which is essentially making sure you are in a browser environment). For most cases, simply wrapping your browser-only code in something like this is sufficient:

if (typeof window !== 'undefined') {
  // browser-only code
}

All 4 comments

Since react-static builds static versions of your site, most times you'll need to make sure the window object is available (which is essentially making sure you are in a browser environment). For most cases, simply wrapping your browser-only code in something like this is sufficient:

if (typeof window !== 'undefined') {
  // browser-only code
}

Hi guys !

Is React static can be used in other context than browser ?
If no, could we assume document and window are globally available and get rid on conditionnal imports and stuff like that everywhere ? Or better, an option to make some variables globally accessible in the react static config, to let the project versatile.

let SmoothScroll
if (typeof window !== 'undefined') {
    SmoothScroll = require('smooth-scroll')
}

this exemple works, but when you are using multiple front libraries it quickly become a mess ^^

What you think ?

Hello, I'm also having troubles with window variable.

When I run react-static start the bundle compiles successfully, even though I have things like

componentDidMount(){
  window.addEventListener('resize', this.myFlexStyle)
}

But when I run react-static build it fails. Why does the first command above succeed?

You must write node safe code. Using window without a document check will error in the build stage because there is no DOM. https://react-static.js.org/docs/concepts#writing-universal-node-safe-code

Was this page helpful?
0 / 5 - 0 ratings