Gatsby graphql 查询 GatsbyImage 以使用项目中的本地图像

Ras*_*rin 4 reactjs graphql gatsby gatsby-image

我只想使用 GatsbyImage 组件来使用图像。

通常你使用<img src='./img.jpg'/>. GatsbyImage是如何完成的,所以我可以使用 props 发送图像。

Fer*_*reu 5

如果您想使用,GatsbyImage则需要提供 Gatsby 使用其转换器和锐器推断的额外 GraphQL 节点数据。为此,您需要通过在以下位置设置以下代码片段来告诉 Gatsby 这些图像在您的位置gatsby-config.js

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `componentImages`,
    path: `${__dirname}/src/components`,
  },
},
Run Code Online (Sandbox Code Playgroud)

注意:您可以有多个实例gatsby-source-filesystem

再次启动gatsby develop刷新源后,您将在 GrahiQL 游乐场 ( ) 中看到可用的节点,localhost:8000/___graphql您应该在其中测试查询,但它应该如下所示:

  image: file(relativePath: {eq: "free-time.jpg"}) {
    childImageSharp {
      gatsbyImageData
    }
  }
Run Code Online (Sandbox Code Playgroud)

在您的 CodeSandbox 中进行测试并正常工作。