【问题标题】:Conditionally import module using next js dynamic import, SSR doesn't work使用next js动态导入有条件导入模块,SSR不起作用
【发布时间】:2021-06-21 19:20:10
【问题描述】:

我有一个组件,我使用来自 nextjs 的 dynamic 动态导入。而且我也想根据我在代码中设置的标志下载捆绑包(下面的代码块中的 loadWirelessBundle 标志)。因此,它在下载捆绑包但渲染组件方面工作正常但它不会对组件进行服务器端渲染(当 loadWirelessBundle 为 true 时),即使我正在传递 ssr = true。有谁知道它为什么不做服务器端渲染?

const WirelessPrepaid = loadWirelessBundle ? dynamic(() => import("../wireless-prepaid"), { ssr: true }) : () => null;

在理解使用 nextjs 的动态导入方面,我有什么遗漏吗?有人可以帮忙吗?谢谢!

【问题讨论】:

  • 您能说明一下您是如何设置loadWirelessBundle 标志的吗?

标签: reactjs webpack next.js


【解决方案1】:

您需要在顶层进行导入

// this goes at the top level of the module
const WirelessPrepaidDynamicComponent = dynamic(() => import("../wireless-prepaid"));

// this can be placed wherever you need it

const WirelessPrepaid = loadWirelessBundle ? WirelessPrepaidDynamicComponent  : () => null;


【讨论】:

    【解决方案2】:

    首先,ssr 不需要显式传递为true,默认只启用。

    其次,loadWirelessBundle 的值可能是在客户端而不是在服务器端设置的,因此组件在客户端被导入。所以我们可能不得不在服务器端设置它的值,看看它是否有效。

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2021-09-03
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      相关资源
      最近更新 更多