page-data.json 中失败页面“/”的页面数据

Page data from page-data.json for the failed page "/"

我在 运行 gatsby 构建时遇到此错误。我没有在我的代码中使用“文档”。谁能解释一下这是什么意思?

ERROR

Page data from page-data.json for the failed page "/": {
"componentChunkName": "component---src-pages-index-js", "path": "/", "result": { "pageContext": {} }, "staticQueryHashes": [] }

failed Building static HTML for pages - 2.990s

ERROR #95312

"document" is not available during server side rendering.

出现这个问题的原因是因为在你的代码中某处你正在使用 document 全局对象,并且因为 gatsby develop 是由浏览器呈现的,其中有 window 和记录全局对象,它会编译,但是,当您 运行 gatsby build 时,代码是在 Node 服务器中编译的,那里没有 windowdocument 变量,因为它们不是即使尚未定义,它们也是在 SSR 中解析的 client-side 变量(Server-Side R渲染).

这是对正在发生的事情的极度简化,您可以在 Debugging HTML Builds docs 中找到更详细的解释。

对于fix/bypass这个问题,只需要在使用document对象的地方添加如下条件即可。

 if(window !== "undefined"){
   // your document or window manipulation
 }

你可以在条件中同时使用windowdocument,它们在绕过server-side渲染方面是等价的。

如果您没有在您的项目中使用 document,如果您的某些依赖项 (third-party) 正在使用它(即:canvas、地图、 sliders 使用 JavaScript 计算等)。如果这是你的情况,绕过它的方法是通过添加 null 加载程序来忽略 webpacks 捆绑:

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

其中 /bad-module/ 是一个正则表达式 (test)(这就是为什么在斜杠之间,/)。在这种情况下,您需要将 node_modules.

中的依赖文件夹名称替换为 bad-module