如何在 gatsby 中获取 Markdown 文件的目录名称?

Meb*_*tte 1 javascript reactjs gatsby

我有一个帖子目录,如:

src
  -posts
    -post-a
      index.md
      demo.jpg
    -post-b
      index.md
      logo.jpg
  -pages
    index.js
    // ...
Run Code Online (Sandbox Code Playgroud)

我想让目录名 post-a/post-b 作为 index.md 的 id,我该怎么做?

这是我的gatsby-config.js

src
  -posts
    -post-a
      index.md
      demo.jpg
    -post-b
      index.md
      logo.jpg
  -pages
    index.js
    // ...
Run Code Online (Sandbox Code Playgroud)

allMarkdownRemark.edges.node没有目录信息。

Lek*_*rts 5

您可以使用createFilePathfrom 函数gatsby-source-filesystem构建您的 slug 并markdownRemark.fields使用onCreateNodeAPI将其添加到。官方博客启动器也这样做:https : //github.com/gatsbyjs/gatsby-starter-blog/blob/04ace724603b46198665e052006031ba7e644f9d/gatsby-node.js#L53-L64

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

slug 现在包含您的博客文章的目录名称。


你原来的问题:

您可以使用联合类型来访问父级,例如:

{
  allMarkdownRemark {
    nodes {
      parent {
        ... on File {
          dir
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)