【问题标题】:gatsby develop works but not build on same project盖茨比开发作品,但不是建立在同一个项目上
【发布时间】:2021-04-09 13:31:09
【问题描述】:

我有一个非常简单的 Gatsby 应用程序。我正在运行 gatsby develop 并且它工作正常但是当我运行 gatsby build 时出现错误。我不确定为什么开发会起作用而构建不会。不知道我错过了什么!

import React from "react"

import Layout from "./layout"

const ProductTemplate = ({ pageContext }) => {
const { product } = pageContext
return (
  <Layout>
    <h1>{product.title}</h1>
    <div>{product.description}</div>

  </Layout>
  )
}

export default ProductTemplate

这是确切的错误

   8 |   return (
   9 |     <Layout>
> 10 |       <h1>{product.title}</h1>
     |                    ^
  11 |       <div>{product.description}</div>
  12 | 


  WebpackError: TypeError: Cannot read property 'title' of undefined

  - product.js:10 
  src/pages/product.js:10:20

gatsby-node.js

const path = require(`path`)
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
// Query for all products in Shopify
const result = await graphql(`
  query {
    allShopifyProduct(sort: { fields: [title] }) {
      edges {
        node {
          title
          shopifyId
          handle
          description
          availableForSale
          priceRange {
            maxVariantPrice {
              amount
            }
            minVariantPrice {
              amount
            }
          }
        }
      }
    }
  }
`)
// Iterate over all products and create a new page using a template
// The product "handle" is generated automatically by Shopify
result.data.allShopifyProduct.edges.forEach(({ node }) => {
  createPage({
    path: `/product/${node.handle}`,
    component: path.resolve(`./src/pages/product.js`),
    context: {
      product: node,
    },
  })
})
}

【问题讨论】:

  • 你能分享你的gatsby-node.js吗?
  • 用 gatsby-node.js 更新帖子

标签: node.js build graphql gatsby production


【解决方案1】:

您的ProductTemplate/pages 文件夹中(它应该在/templates 中)。这导致 Gatsby 尝试自动为该目录中的每个文件创建页面。在它自动执行的情况下,它不会获得任何上下文,因此构建失败。这仅在您运行 gatsby build 时发生,因为在 gatsby develop 期间没有 SSR(Server-Side Rendering)。

createPage API 旨在基于 slug、路径或其他唯一标识符字段创建动态页面,而不是用于像 /pages 文件夹内的已知页面。

要修复它,只需将您的 product.js 移动到 /templates 并更改:

component: path.resolve(`./src/pages/product.js`),

到这里:

component: path.resolve(`./src/templates/product.js`),

这是因为您正在为每个产品创建模板,而不是页面(就像 Gatsby 理解页面一样)。

Here's a GitHub thread 如果您想了解完整的解释,您的问题正是如此。

【讨论】:

  • 谢谢。这似乎只解决了部分问题。现在我看到了。错误 #98124 WEBPACK undefined failed 无法解析 '/Users/Test/Downloads/my-gatsby/gatsby-site/src/templates' 中的 './layout' 如果您尝试使用包,请确保 '. /布局'已安装。如果您尝试使用本地文件,请确保路径正确。
  • 没关系,我想我知道这里有什么问题。
  • 我很乐意提供帮助。这个新问题是因为,由于您更改了 ProductTemplate 位置,因此您必须重新排列导入以匹配工作位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 2020-09-15
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多