next. js
In your page components, you can execute code only in the server-side or on the client-side, but checking the window
property.
在页面组件中,您只能在服务器端或客户端执行代码,但可以检查window
属性。
This property is only existing inside the browser, so you can check
此属性仅存在于浏览器内部,因此您可以检查
if (typeof window === 'undefined') {
}
and add the server-side code in that block.
并在该块中添加服务器端代码。
Similarly, you can execute client-side code only by checking
同样,您只能通过检查执行客户端代码
if (typeof window !== 'undefined') {
}
JS Tip: We use the
typeof
operator here because we can’t detect a value to be undefined in other ways. We can’t doif (window === undefined)
because we’d get a “window is not defined” runtime errorJS技巧:我们在这里使用
typeof
运算符是因为我们无法通过其他方式检测到未定义的值。 我们无法执行if (window === undefined)
因为我们会收到“if (window === undefined)
窗口”的运行时错误
Next.js, as a build-time optimization, also removes the code that uses those checks from bundles. A client-side bundle will not include the content wrapped into a if (typeof window === 'undefined') {}
block.
Next.js作为构建时的优化,也从捆绑软件中删除了使用这些检查的代码。 客户端捆绑包将不包含包装在if (typeof window === 'undefined') {}
块中的内容。
next. js