【问题标题】:Gatsby.js - GraphQL Query pdf file in allMarkdownRemarkGatsby.js - GraphQL 查询 pdf 文件在 allMarkdownRemark
【发布时间】:2019-06-18 10:56:45
【问题描述】:

我目前正在为一个学校项目构建一个 gatsby 网站,但遇到了一些我自己无法弄清楚的东西。

基本上我有一些降价文件。它们包含一个名为“file”的 frontmatter 字段,其中另一个文件的名称(例如:“test.pdf”)作为值。 我需要知道这些文件的公共 URL。

我试着这样写我的查询:

     query SiteQuery{
           publications: allMarkdownRemark(
               filter: { fileAbsolutePath: {regex : "/publications/"} },
               sort: { order: DESC, fields: [frontmatter___date] },
           ){
             edges {
               node {
                 frontmatter {
                   date(formatString: "MMMM DD, YYYY"),
                   title,
                   file{
                     publicURL                   
                   }
                 }
              }
            }
         }
    }

但它总是将字段“文件”解释为字符串,我认为这很奇怪,因为我已经对这样的图像执行了相同的过程:

...
    node {
      frontmatter {
        date(formatString: "MMMM DD, YYYY"),
        title,
        picture {
          childImageSharp {
            fluid{
              ...GatsbyImageSharpFluid
            }
          }
        }
      } 
    } 
...

我已经搜索过答案,但我能找到的最有用的结果是在这个网站上:https://www.gatsbyjs.org/docs/adding-images-fonts-files/

但我无法让它工作。

谁能告诉我我在这里做错了什么?

当然,我总是可以使用 'allFile' 编写第二个查询,然后通过绝对路径将 markdown 文件与 pdf 文件匹配,但我希望有比这更好的解决方案。

【问题讨论】:

    标签: javascript reactjs graphql gatsby


    【解决方案1】:

    这是您想要使用 mapping 的时候,但对于不是 Markdown 或 JSON 文件的任何内容都没有很好的文档记录。

    gatsby-config.js - 映射

    // NOTE: the frontmatter `file` and property `base` must have unique values
    // That is, don't allow any files to have the same name if mapping `base`
    mapping: {
        'MarkdownRemark.frontmatter.file' : 'File.base',
    }
    

    所以现在你可以成功了:

    query SiteQuery{
        publications: allMarkdownRemark(
            filter: { fileAbsolutePath: {regex : "/publications/"} }
            sort: { order: DESC, fields: [frontmatter___date] }
        ){
           edges {
               node {
                   frontmatter {
                       date(formatString: "MMMM DD, YYYY")
                       title
                       file {
                           publicURL                   
                       }
                   }
               }
           }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2019-02-20
      • 2021-05-28
      • 2020-06-20
      • 2020-01-20
      • 2018-07-09
      • 2019-12-26
      • 2021-04-07
      • 2020-10-13
      相关资源
      最近更新 更多