I thought checking for if (typeof window === 'undefined')
would remove the if clause and its contents in a Next.js production build in the client bundle? Has this been changed somehow in Next.js 11 or 12 or Webpack 5?
The next-code-elimination tool doesn't do it, but perhaps that tool is just not supporting getInitialProps
anymore, only getServerSideProps
? Or is the actual production build also not supporting dead code elimination in getInitialProps
anymore?
Any pointers appreciated... (I found this bug report but it's pretty old and closed, and the 2017 blog post SSR and Server Only Modules, which doesn't mention typeof window
checking).
Minimal reproducible example:
export const Content = () => {
return <h1>hello</h1>
}
Content.getInitialProps = async () => {
if (typeof window === 'undefined') {
const article = await 'foo'
return 'server'
}
}
The problem seems to be the await
keyword! But even if I move the async stuff out to a helper function and don't use await
inside getInitialProps
, if the helper function contains moderately complex code, webpack seems to inline it and we're back to step one.