別のディレクトリに分けておいた md や mdx を各ディレクトリ毎に取得したいことがあった。ただ、gatsby-transformer-remarkやgatsby-plugin-mdxで使えるようになるallMarkdownRemark
やallMdx
を使うと、基本的にgatsby-source-filesystemで FileNode に追加したすべての md(mdx)を取得してしまう。
fileAbsolutePath を使う
手っ取り早いのは正規表現を使ってfileAbsolutePath
をフィルタリングする方法。
allMdx(filter: {fileAbsolutePath: {regex: "/dir1/"}}) {
nodes {
id
}
}
基本的にはこの方法で問題なさそう。
sourceInstanceName を使う
正規表現を使う方法でまあ十分だけどもう少しスマートな方法がないかと調べているといい感じの方法が紹介されてた。
gatsby-source-filesystem ではsourceInstanceName
(オプションの name)を指定することができる。このsourceInstanceName
は FileNode にはあるけど、残念ながら Markdown(Mdx)Node には含まれてない。そこで、これを Markdown(Mdx)Node に追加する。
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `Mdx`) {
const value = getNode(node.parent).sourceInstanceName
createNodeField({
name: `sourceInstanceName`,
node,
value,
})
}
}
するとsourceInstanceName
が使えるようになるので以下のようにフィルタリングできる。
allMdx(filter: {fields: {sourceInstanceName: {eq: "dir1"}}}) {
nodes {
id
}
}