Preact-cli: Template execution failed: ReferenceError: window is not defined

Created on 7 Jun 2017  路  6Comments  路  Source: preactjs/preact-cli

How can I use a window/document API?

It works fine on dev, but when i run npm run build I am getting

Template execution failed: ReferenceError: window is not defined

Most helpful comment

Preact-cli prerender your view on build step (using SSR technique). So you have 2 ways to solve this:

  1. Disable prerender. Use the command to build preact build --no-prerender
  2. Wrap window/document API like this
if (typeof window !== "underfined") {
 // Do stuff here
}

All 6 comments

Preact-cli prerender your view on build step (using SSR technique). So you have 2 ways to solve this:

  1. Disable prerender. Use the command to build preact build --no-prerender
  2. Wrap window/document API like this
if (typeof window !== "underfined") {
 // Do stuff here
}

@thangngoc89 thx a lot!

Question, are we missing anything by adding the no-prerender?

You might miss out on a little performance boost, but it's minimal. The usefulness of prerendering varies a lot based on what type of app you're building. If you're building a content website and all your content is synchronously available, it'll prerender quite nicely. If you're building something like a messaging application (just an example), prerendering is very unnecessary. Often times pre-rendering these types of applications just gets your loading spinner on the screen a little faster, which is a meager gain.

@developit i'm trying to use the preact-mdl with the preact-cli template. I'm new to preact/react so this could just be my lack of understanding but when I do the standard import mdl from 'material-design-lite/material'; which works fine on dev is failing on preact build and im getting
Error: ENOENT: no such file or directory, open 'src/~/material-design-lite/dist/material.js
along with an output similar to whats on this thread. I cant wrap the import in if (typeof window !== "underfined"). Suggestions would be really appreciated, i'd prefer not to use --no-prerender as I think prerender will be really beneficial to my use case

@endamccormack your issue might not be the same with this issue. Could you open a new issue with full stack trace?

FYI, you can require in the if check

if (typeof window !== "underfined") {
  require("..")
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

hardcoar picture hardcoar  路  3Comments

ethanwu10 picture ethanwu10  路  3Comments

jpoo90 picture jpoo90  路  4Comments

AlStar01 picture AlStar01  路  3Comments

hesselbom picture hesselbom  路  3Comments