使用imageSharp regex和gatsby的graphQL中出现错误

时间:2018-08-25 20:15:23

标签: regex graphql gatsby

我正在使用gatsby创建一个简单的博客。当我尝试搜索特定图像时,出现来自graphql的错误。我有以下配置:

已安装"gatsby-image": "^1.0.55"

graphql`
      query MainLayoutQuery {
        heroImage: imageSharp(id: { regex: "/hero.jpg/" }) {
          id
          sizes(quality: 100) {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    `

当我在graphql ui中运行该查询时,我得到:

{
  "errors": [
    {
      "message": "Cannot read property 'id' of undefined",
      "locations": [
        {
          "line": 31,
          "column": 3
        }
      ],
      "path": [
        "heroImage"
      ]
    }
  ],
  "data": {
    "heroImage": null
  }
}

但是,如果我在不使用正则表达式的情况下运行相同的查询,则效果很好:

{
  heroImage: imageSharp {
    id
    sizes(quality: 100) {
      base64
      tracedSVG
      aspectRatio
      src
      srcSet
      srcWebp
      srcSetWebp
      sizes
      originalImg
      originalName
    }
  }
}

当然,它会带来它可以访问的第一张图片

"data": {
    "heroImage": {
      "id": "/Users/marcosrios/dev/workspace/atravesando-todo-limite/src/posts/2018-08-25-tengo-miedo/cover.png absPath of file >> ImageSharp"
    }
}

1 个答案:

答案 0 :(得分:4)

您正在使用哪个版本的盖茨比?如果v2由于有更改,则需要编辑查询: https://next.gatsbyjs.org/docs/migrating-from-v1-to-v2/#dont-query-nodes-by-id

您的查询将如下所示:

graphql`
      query MainLayoutQuery {
        heroImage: imageSharp(fluid: { originalName: { regex: "/hero.jpg/" } }) {
          id
          fluid(quality: 100) {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    `