next.js使用koa_如何在需要窗口的Next.JS中使用库

next.js使用koa

How to use a library that expects to be running in a browser, but is breaking when rendered server-side in the node.js environment, or, how to make react-chat-widget work in next.js.

如何使用期望在浏览器中运行但在node.js环境中在服务器端呈现时会中断的库,或者如何在next.js中使react-chat-widget工作。

This article uses the Korerorero project as an example. Korerorero is an open source implementation of an animated chatbot with voice recognition.

本文以Korerorero项目为例。 Korerorero是具有语音识别功能的动画聊天机器人的开源实现。

For korerorero-front-end to implement react-chat-widget in its next.js framework, SSR broke because react-chat-widget assumes it’s running in a browser environment and so has access to the window object. The window object is not available on the server-side node.js environment.

为了让korerorero前端在next.js框架中实现react-chat-widget ,SSR失败了,因为react-chat-widget假定它在浏览器环境中运行,因此可以访问window对象。 该window对象在服务器端的node.js环境中不可用。

To work around this mismatch in assumptions, the next.js feature dynamic-import came to the rescue. Its stated intent is to break an app into chunks, allowing lazy loading, and so, speeding up the initial page render. In this case, it can be used to make sure that code with references to the browser’s window object only ever executes in the browser.

为了避免这种假设上的不匹配,使用了next.js 动态导入功能。 声明的目的是将应用程序分成多个块,允许延迟加载,从而加快初始页面渲染的速度。 在这种情况下,可以用来确保引用浏览器窗口对象的代码仅在浏览器中执行。

ChatWidget.jsx (ChatWidget.jsx)

Source: https://github.com/nzcodarnoc/korerorero-front-end/blob/main/src/components/ChatWidget.jsx

来源: https : //github.com/nzcodarnoc/korerorero-front-end/blob/main/src/components/ChatWidget.jsx

Here’s what happens in the example above. On line 4 a promise is created, which will resolve to the variable mod when the library is loaded. Then the fully initialized Widget is available as a property on mod.

这是上面示例中发生的情况。 在第4行上,创建了一个promise,它将在加载库时解析为变量mod 。 然后,可以将完全初始化的Widget作为mod的属性使用。

On line 6 the call to dynamic is configured with an option that tells the framework only to invoke the import in the browser environment.

在第6行上,对dynamic的调用配置了一个选项,该选项告诉框架仅在浏览器环境中调用导入。

Good times at the SSR coral.

SSR珊瑚的美好时光。

翻译自: https://medium.com/swlh/how-to-use-a-library-in-next-js-that-wants-window-whatever-96c738263d67

next.js使用koa

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值