Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - Window is not defined in Next.js React app

In my Next.js app I can't seem to access window:

Unhandled Rejection (ReferenceError): window is not defined

componentWillMount() {
    console.log('window.innerHeight', window.innerHeight);
}

Enter image description here

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another solution is by using p?r?o?c?e?s?s?.?b?r?o?w?s?e?r to just execute your command during rendering on the client side only.

But process object has been deprecated in Webpack5 and also NextJS, because it is a NodeJS variable for backend side only.

So we have to use back window object from the browser.

if (typeof window !== "undefined") {
  // Client-side-only code
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...