简体   繁体   English

禁用 next.js 服务器端呈现以防止 window 未定义错误

[英]disabling next.js server side rendering to prevent window is undefined errors

I have a private NPM package that I maintain, which I use in a Next.js project.我有一个我维护的私有 NPM package,我在一个 Next.js 项目中使用它。 Both projects are React, Typescript projects.两个项目都是React,Typescript个项目。

I've recently added a graph into the NPM project and have now run into the problem of;我最近在 NPM 项目中添加了一个图表,现在遇到了以下问题: all the calls to window within that NPM package throw an error window is undefined within the Next.js project在 NPM package 中对 window 的所有调用都会抛出错误window is undefined

As I'm using a library, that I don't have control over, to build my graph, I don't have the luxury of wrapping the calls to window in some sort of if (typeof window !== "undefined") statement.当我使用一个我无法控制的库来构建我的图表时,我没有奢侈地将对 window 的调用包装在某种if (typeof window !== "undefined")中陈述。

I get these errors on build of my Next.js project, before I've even made a call to a component that makes use of the graphing library.我在构建 Next.js 项目时遇到了这些错误,甚至在调用使用图形库的组件之前。 Simply including my NPM package in my main project results in these errors arising.简单地将我的 NPM package 包含在我的主要项目中会导致出现这些错误。

Would it be possible to stop server-side rendering just for that particular graphing library or perhaps my entire NPM package?是否可以仅针对特定图形库或我的整个 NPM package 停止服务器端渲染?

Alternatively any other solution would be welcome, however wild.或者,欢迎任何其他解决方案,无论多么疯狂。

Given the constrain you mentioned.鉴于您提到的限制。 I don't think there are much options.我认为没有太多选择。 You simply don't have window object in node environment.您根本没有window object 在node环境中。

You can render other parts of the page where SSR is possible.您可以呈现页面的其他可能存在 SSR 的部分。 and you can dynamically render with ssr: false for the portion where you cannot SSR due to window object.对于由于window object 而无法 SSR 的部分,您可以使用ssr: false动态渲染。

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>
  )
}

Reference:参考:

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

Maybe you can try dynamic import your graph import也许你可以尝试动态导入你的图形导入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM