【问题标题】:Gatsby develop command runs but gatsby build gives errorGatsby develop 命令运行但 gatsby build 给出错误
【发布时间】:2019-06-21 11:06:19
【问题描述】:

我正在使用 gatsby-node.js 文件动态创建页面

let allProducts = result.data.allProducts.edges
    createPage({
        path: `/products`,
        component: require.resolve('./src/pages/products.js'),
        context: { allProducts }
    });

  //Create a page for each Product.
  allProducts.map((edge)=>{
    let product = edge.node
    createPage({
      path:`/product/${product.id}`,
      component: require.resolve('./src/pages/product.js'),
      context:{product}
    })
  })

Gatsby 开发运行良好,但是当我执行 gatsby 构建时出现错误

错误为页面构建静态 HTML 失败

请参阅我们有关调试 HTML 构建的文档页面以获取帮助 https://gatsby.app/debug-html

  43 |         <div >
  44 |             <Img fluid={data.bannerHeaderProduct.childImageSharp.fluid}/>
> 45 |             <img src={product.imgSrc }alt=""/>
     |                               ^
  46 |         </div>
  47 |         <div>
  48 |             <h3 dangerouslySetInnerHTML={{__html:product.name}}>

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

我作为上下文传递给页面的产品变得未定义

【问题讨论】:

    标签: javascript node.js reactjs graphql gatsby


    【解决方案1】:

    看到您的代码,它会正常工作。 createPage 结构没问题。

    根据我的经验,有时 gatsby/graphql 错误发射器不会显示正确的错误行,如果有许多具有相同名称的变量 (imgSrc) gatsby 错误发射器会显示第一个出现的变量,而不是错误的。

    确认您应该在返回渲染检查产品是否未定义之前放置一个“if”。这是防止构建期间呈现错误的好方法:

    render(){
       const {product} = this.props.pathContext;
    
       if(product === undefined) return null;
    
       ......
    
       return <div>....</div>;
    }
    

    您还可以在 gatsby-node 中放置一个 console.log,显示“allProducts”和“product”变量,在构建过程中检查变量结构。

    你能回复一下结果吗?

    【讨论】:

      【解决方案2】:

      一个简单的解决方法是将页面文件夹重命名为模板(并在 gatsby-node 中的路径中更改它)

      【讨论】:

      • 在使用 gatsby-plugin-create-client-paths 时也遇到了这个问题,并且修复(尽管它在开发中工作并且在以前的构建 afaik 中工作过)是将文件从 pages 移动到 templates文件夹
      • 解释:src/pages 中的页面默认被使用,当重用该目录中的文件时,它会被多次调用并加上一次自动
      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 2020-06-22
      • 2020-02-06
      • 2021-03-16
      • 1970-01-01
      相关资源
      最近更新 更多