error in graphQL using imageSharp regex with gatsb

2019-08-01 05:52发布

I'm using gatsby to create a simple blog. When I try to search for an specific image, I get an error from graphql. I have the following configs:

installed "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
          }
        }
      }
    `

when I run that query in graphql ui I get:

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

But, if I run the same query without the regex, it works fine:

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

Of course, it brings the first image it has access to

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

1条回答
狗以群分
2楼-- · 2019-08-01 06:20

Which version of Gatsby are you using? If v2 you need to edit your query as there has been changes: https://next.gatsbyjs.org/docs/migrating-from-v1-to-v2/#dont-query-nodes-by-id

Your query then would look like that:

graphql`
      query MainLayoutQuery {
        heroImage: imageSharp(fluid: { originalName: { regex: "/hero.jpg/" } }) {
          id
          fluid(quality: 100) {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    `
查看更多
登录 后发表回答