通过relativepath访问文件的GraphQL语法

通过relativepath访问文件的GraphQL语法,graphql,gatsby,Graphql,Gatsby,GatsbyJS给出了通过relativepath和GraphQL访问文件的示例: export const query = graphql` query { fileName: file(relativePath: { eq: "images/myimage.jpg" }) { childImageSharp { fluid(maxWidth: 400, maxHeight: 250) { ...GatsbyImageSharpFlu

GatsbyJS给出了通过relativepath和GraphQL访问文件的示例:

export const query = graphql`
  query {
    fileName: file(relativePath: { eq: "images/myimage.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`
我就是不能让它工作,我不知道为什么。我尝试了各种不同的语法,但查询总是返回null作为文件名。这是我最近在GraphiQL中的尝试:

{
    fileName: file(relativePath: { eq: "./html.js" }) {
      id
    } 
}
我错过了什么?如何通过相对路径访问文件

阅读答案后编辑:

在my
gatsby config.js
中,有几个路径设置为可查询:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/images/`
  }
},
{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/content/posts/`,
    name: "posts"
  }
},
....

当我查询
pic.jpg
(而不是
images/pic.jpg
)时,盖茨比怎么知道我想要
images/pic.jpg
而不是
posts/pic.jpg
?这是如何唯一地定义路径的?

文件节点的
相对路径
字段相对于您在
gatsby源文件系统
中指定的目录

例如,假设我有如下目录结构:

root
  |--gatsby-config.js
  `--dirA
      |--fileA.md
      `--dirB
          |--fileB.md
          `--dirC
               `--fileC.md
query {
  fileName: file(relativePath: {
    eq: "dirB/dirC/fileC.md"
  }) {
    id
  }
}
在我的
gatsby config.js

{
解析:`gatsby源文件系统`
选项:{

路径:“${uuu dirname}/dirA`,让我吃惊的是,根据需要,您需要重新启动
gatsby develope
,以便刷新GraphQL数据(即,在您调整
relativePath
之后)

这可以通过以下方式解决:

  • 使用
    ENABLE\u Gatsby\u REFRESH\u ENDPOINT=true Gatsby develop启动Gatsby
  • 每次要刷新数据时,在单独的终端中运行
    curl-X POST localhost:8000/\uu refresh

再次感谢您!这是有效的,尽管我仍然想知道这是如何唯一地定义路径的?我编辑了OP以澄清我的意思。@AtteJuvonen Hi Atte!我已经更新了答案以解决编辑后的问题。简言之,如果您仅依赖于
relativePath
,盖茨比将不知道您想要哪个文件,只会返回它能找到的第一个。你必须添加额外的过滤器,以确保文件是唯一的。或者,你也可以通过其
绝对路径
字段查询文件节点,在这种情况下,你不需要通过额外的过滤器。这是一个非常好的答案,需要评论,而不仅仅是投票。:-)这似乎不太清楚在手术室。谢谢。回答得很好!
query {
  fileName: file(relativePath: {
    eq: "dirB/dirC/fileC.md"
  }) {
    id
  }
}
root
  |--gatsby-config.js
  |--dirD
  |   `--index.md
  `--dirE
      `--index.md
query {
  fileName: file(relativePath: {
    eq: "index.md"
  }) {
    id
  }
}
{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/dirE`,
    name: `dirE`,
  },
},
{
  file(
    relativePath: {
      eq: "index.md"
    },
    sourceInstanceName: {
      eq: "dirE"
    }
  ) {
    id
  }
}
query {
  allFile(filter: {
    relativePath: { eq: "index.md" }
  }) {
    edges {
      node { 
        id
      }
    } 
  }
}