Gatsby/webpack - WebpackError window is not defined - 在哪里?

5
在运行gatsby build时,我遇到了以下错误。
我知道如何解决它(例如检查window的typedef),但我找不到使用window的地方?我怀疑是一个Node模块,因为在我的代码中没有太多window的引用。
非常感谢。
failed Building static HTML for pages - 10.845s

 ERROR #95312 

"window" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html





  WebpackError: ReferenceError: window is not defined
  
  - build-html.js:110 doBuildPages
    /[gatsby]/dist/commands/build-html.js:110:24
  
  - build-html.js:124 async buildHTML
    /[gatsby]/dist/commands/build-html.js:124:3
  
  - build.js:206 async build
    /[gatsby]/dist/commands/build.js:206:5
4个回答

2

一次删除一个第三方节点包,以找到有问题的模块。然后你需要分叉该包并修复它,以使其不使用window对象,或者找到替代包。


2

感谢所有其他答案。

我尝试了@Raz Ronen的答案,但是更改globalObject会导致其他问题,比如未定义的localStorage。

我尝试删除所有节点模块,但没有帮助。

奇怪的是,在删除节点模块后,错误发生了变化,我可以看到错误的行!它在Gatsby自己的“navigate”方法中。

我的应用程序中有类似于文档中所解释的私有路由:在文档中

mport React from "react"
import { navigate } from "gatsby"
import { isLoggedIn } from "../services/auth"

const PrivateRoute = ({ component: Component, location, ...rest }) => {
  if (!isLoggedIn() && location.pathname !== `/app/login`) {
    navigate("/app/login")
    return null
  }

  return <Component {...rest} />
}

export default PrivateRoute

但是,我必须将导航放在 useEffect 钩子内部,以便像这样解决问题:

const PrivateRoute = ({ component: Component, location, ...rest }) => {
  const user = useContext(AuthenticationContext)
  useEffect(() => {
    checkLoginStatus()
  }, [])

  const checkLoginStatus = () => {
    if (!user && location.pathname !== `/login`) {
      navigate("/login")
    }
  }

  return <Component {...rest} />
}

1
你可以尝试在编程导航中不使用 Gatsby(它会做一些额外的事情)。尝试使用 @reach/routeruseNavigate 方法。它应该作为一个名为 navigate 的 prop 传递进去,但为了确保,请直接导入它:import { useNavigate } from "@reach/router" - apena

1
也许设置globalObject会有所帮助。
output: {
    globalObject: "this",
  }

全局对象的默认值是window

1

正如您所说,如果您的代码中没有使用window(修复方法是检查是否使用typeof定义),则问题来自于其中一个第三方依赖项,在其自己的代码中将window用作全局对象。

您必须找出哪个依赖项,并在webpack配置中添加一个null加载器。在您的gatsby-node.js文件中:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /bad-module/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}

在上面的代码中,/bad-module/ 是你想要避免转译的 node_modules 依赖项。基本上,在服务器渲染期间,你将有问题的模块替换为一个虚拟模块。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接