GraphQL语法按相对路径访问文件

阿特·朱沃宁(Atte Juvonen)

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

export const query = graphql`
  query {
    fileName: file(relativePath: { eq: "images/myimage.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`

我只是无法正常工作,也不知道为什么。我尝试了各种不同的语法,但查询始终为文件名返回null。这是我在Graph i QL中的最新尝试

{
    fileName: file(relativePath: { eq: "./html.js" }) {
      id
    } 
}

我想念什么?如何通过相对路径访问文件?

阅读答案后进行编辑:

在我中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这如何唯一地定义路径?

德里克·阮

relativePath文件”节点字段相对于您在中指定的目录gatsby-source-filesystem

例如,假设我有这样的目录结构:

root
  |--gatsby-config.js
  `--dirA
      |--fileA.md
      `--dirB
          |--fileB.md
          `--dirC
               `--fileC.md

在我的 gatsby-config.js

{
  resolve: `gatsby-source-filesystem`
  options: {
    path: `${__dirname}/dirA`, <---- root/dirA
    name: `dir`,
  },
}

里面的文件dirA将具有以下内容relativePath

File      |  relativePath
---------------------------------
fileA.md  |  'fileA.md'
---------------------------------
fileB.md  |  'dirB/fileB.md'
---------------------------------
fileC.md  |  'dirB/dirC/fileC.md'

我可以这样查询fileC

query {
  fileName: file(relativePath: {
    eq: "dirB/dirC/fileC.md"
  }) {
    id
  }
}

因此,在您的情况下,您可以指向gatsby-source-filesystem的父目录html.js,并且该目录应该是可查询的。


获取唯一文件

如果我具有以下结构:

root
  |--gatsby-config.js
  |--dirD
  |   `--index.md
  `--dirE
      `--index.md

并指向gatsby-source-filesystem它们两个,现在有2个具有相同relativePathindex.md)的文件节点

在这种情况下,执行以下查询是不安全的:

query {
  fileName: file(relativePath: {
    eq: "index.md"
  }) {
    id
  }
}

因为它将返回满足过滤条件的第一个File节点(我不确定gatsby如何确定文件顺序,如果有人知道,请分享!)。添加一些其他唯一过滤器会更安全。

例如,当我设置时gatsby-source-filesystem,我可以指定一个name属性。name将存储在“sourceInstanceName文件”节点上字段中。

{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/dirE`,
    name: `dirE`,
  },
},

我可以这样查询它:

{
  file(
    relativePath: {
      eq: "index.md"
    },
    sourceInstanceName: {
      eq: "dirE"
    }
  ) {
    id
  }
}

我想到的组合sourceInstanceName,并relativePath足以确保文件的唯一性。

或者,您也可以通过其查询文件节点absolutePath这样可以保证文件是唯一的,尽管您仍然需要告诉gatsby-source-filesystem文件在哪里。

如果您想查看所有具有相同文件的文件relativePath,此查询将执行以下操作:

query {
  allFile(filter: {
    relativePath: { eq: "index.md" }
  }) {
    edges {
      node { 
        id
      }
    } 
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章