如何在 gatsby 中获取 markdown 文件的目录名?
How can i get directory name of markdown file in gatsby?
我有一个像这样的帖子目录:
src
-posts
-post-a
index.md
demo.jpg
-post-b
index.md
logo.jpg
-pages
index.js
// ...
我想把目录名post-a/post-b作为index.md的id,怎么办?
这是我的 gatsby-config.js
:
module.exports = {
plugins: [
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'posts',
path: `${__dirname}/src/posts`,
},
},
{
resolve: 'gatsby-transformer-remark',
options: {
commonmark: true,
footnotes: true,
pedantic: true,
gfm: true,
plugins: [],
},
},
'gatsby-transformer-sharp',
'gatsby-plugin-sharp',
'gatsby-plugin-react-helmet',
],
};
但是allMarkdownRemark.edges.node
没有目录信息。
您可以使用 gatsby-source-filesystem
中的 createFilePath
函数构建您的 slug,并使用 onCreateNode
API 将其添加到 markdownRemark.fields
。官方博客启动器也是这样做的: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,
})
}
}
slug 现在包含您博客文章的目录名称。
你原来的问题:
您可以使用联合类型来访问父级,例如:
{
allMarkdownRemark {
nodes {
parent {
... on File {
dir
}
}
}
}
}
我有一个像这样的帖子目录:
src
-posts
-post-a
index.md
demo.jpg
-post-b
index.md
logo.jpg
-pages
index.js
// ...
我想把目录名post-a/post-b作为index.md的id,怎么办?
这是我的 gatsby-config.js
:
module.exports = {
plugins: [
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'posts',
path: `${__dirname}/src/posts`,
},
},
{
resolve: 'gatsby-transformer-remark',
options: {
commonmark: true,
footnotes: true,
pedantic: true,
gfm: true,
plugins: [],
},
},
'gatsby-transformer-sharp',
'gatsby-plugin-sharp',
'gatsby-plugin-react-helmet',
],
};
但是allMarkdownRemark.edges.node
没有目录信息。
您可以使用 gatsby-source-filesystem
中的 createFilePath
函数构建您的 slug,并使用 onCreateNode
API 将其添加到 markdownRemark.fields
。官方博客启动器也是这样做的: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,
})
}
}
slug 现在包含您博客文章的目录名称。
你原来的问题:
您可以使用联合类型来访问父级,例如:
{
allMarkdownRemark {
nodes {
parent {
... on File {
dir
}
}
}
}
}