模块的动态导入在NextJS SSR中产生空对象

发布于 2025-02-11 13:28:46 字数 1112 浏览 0 评论 0原文

因此,我正在尝试使用此库 penumbra 在NextJS项目中。将其添加为依赖关系后,NextJS会丢下窗口未定义的错误,这是有道理的,因为它是服务器端渲染的东西,并且 penumbra 使用对窗口对象的不安全访问。

这是NextJS中的一个常见问题,GoTo解决方案是使用动态导入,如记录在这里/a>。

我尝试了这种方法,返回的结果是一个空的对象:

import("@transcend-io/penumbra").then(mod => {
  console.log(mod.default); // empty object, default export
  console.log(mod.penumbra); // undefined, named export
})

例如:

import("moment").then(mod => {
  console.log(mod.default()); // returns moment object
})

奇怪的是,这与其他模块一起使用, 是有问题的。

这是工作nextjs示例。如果您检查日志,力矩将返回一个矩对象,但是Penumbra返回{}以获取默认导出,并且未定义为指定的一个。

So I am trying to use this library penumbra in a NextJS project. After adding it as a dependency, NextJS will throw an error that window is undefined, which makes sense since it's server-side rendering things and penumbra uses unsafe access to the window object.

This is a common problem in NextJS and the goto solution is to use dynamic imports as documented here.

I tried this approach and the returned result is an empty object:

import("@transcend-io/penumbra").then(mod => {
  console.log(mod.default); // empty object, default export
  console.log(mod.penumbra); // undefined, named export
})

The weird thing is that this works with other modules say moment for example:

import("moment").then(mod => {
  console.log(mod.default()); // returns moment object
})

This leads me to believe that either I am missing something or the module itself is problematic.

Here is a working NextJS example. If you check the logs, moment returns a moment object, but penumbra returns {} for default export and undefined for the named one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文