【问题标题】:disabling next.js server side rendering to prevent window is undefined errors禁用 next.js 服务器端渲染以防止窗口未定义错误
【发布时间】:2020-12-08 00:08:12
【问题描述】:

我有一个我维护的私有 NPM 包,我在 Next.js 项目中使用它。这两个项目都是 React、Typescript 项目。

我最近在 NPM 项目中添加了一个图表,现​​在遇到了问题;该 NPM 包中对 window 的所有调用都会在 Next.js 项目中引发错误 window is undefined

由于我正在使用一个我无法控制的库来构建我的图表,因此我无法将对 window 的调用封装在某种 if (typeof window !== "undefined") 语句中。

我在构建 Next.js 项目时遇到了这些错误,甚至还没有调用使用图形库的组件。简单地将我的 NPM 包包含在我的主项目中会导致出现这些错误。

是否可以仅针对该特定图形库或我的整个 NPM 包停止服务器端渲染?

或者,任何其他解决方案都会受到欢迎,无论多么疯狂。

【问题讨论】:

标签: javascript node.js reactjs typescript next.js


【解决方案1】:

鉴于您提到的约束。我认为没有太多选择。 node 环境中根本没有 window 对象。

您可以渲染页面的其他可以使用 SSR 的部分。并且您可以使用ssr: false 动态渲染由于window 对象而无法进行SSR 的部分。

import dynamic from 'next/dynamic'

// wrap your component that uses the graph lib.
const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/myGraphComponent'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

参考:

https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

【讨论】:

  • 我遇到的问题是我在调用或导入组件之前得到了 window is undefined 错误。只需安装我的 NPM 包就足以引发错误。
【解决方案2】:

也许你可以尝试动态导入你的图表导入

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 2021-12-18
    • 2017-12-30
    • 1970-01-01
    • 2018-04-26
    • 2019-10-18
    • 1970-01-01
    • 2022-01-21
    • 2018-03-23
    相关资源
    最近更新 更多