前面的图像为Gatsby.js

时间:2017-10-12 16:09:48

标签: markdown gatsby

我一直在努力解决这个问题:

我的前面看起来像:

---
path: '/path-to/'
title: 'Title of Post'
indexImage: './img.jpg'
---

将我的图片放在与我的index.md文件相同的文件夹中。

在我的templates/post.js文件中,我有以下一行:

<img src={ post.frontmatter.indexImage }></img>

认为这会吸引前面列出的来源。我的post.js查询是:

export const postQuery = graphql`
  query BlogPostByPath($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        path
        title
        indexImage
      }
    }
  }
`;

以下是错误消息:

GraphQL Error Field "indexImage" of type "File" must have a selection of subfields. Did you mean "indexImage { ... }"?

有关为什么这不起作用的任何想法?我还是盖茨比的新手,所以这可能是一个让我头疼的问题。提前谢谢。

3 个答案:

答案 0 :(得分:3)

  

必须有一系列子字段。你的意思是“indexImage {...}

是错误的关键部分。

任何时候你看到“子字段”和一个字段(如indexImage)和{ ... }这意味着这是一个“对象”类型而不是“标量”(例如字符串,数字,浮点数等) 。)类型。

因此,您的查询应该类似于:

query BlogPostByPath($path: String!) {
  markdownRemark(frontmatter: { path: { eq: $path } }) {
    html
    frontmatter {
      path
      title
      indexImage {
        childImageSharp {
          resolutions(width: 400) {
            width
            height
            src
            srcSet
          }
        }
      }
    }
  }
}

此示例网站介绍了如何使用图像处理查询https://image-processing.gatsbyjs.org/

答案 1 :(得分:2)

删除.cache文件夹,使构建缓存无效。

答案 2 :(得分:0)

如果图像已转换为文件类型,则要使用publicUrl而不是尝试直接使用图像:

      frontmatter {
        path
        title
        indexImage {
          publicUrl
        }
      }

,而不是代码中的

<img src={ post.frontmatter.indexImage.publicUrl } />
相关问题