next. js_Next.js:仅在Next.js的服务器端或客户端运行代码

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 do if (window === undefined) because we’d get a “window is not defined” runtime error

JS技巧:我们在这里使用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') {}块中的内容。

翻译自: https://flaviocopes.com/nextjs-server-client-code/

next. js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值