
JS
Gatsby 是一个基于 React 的静态网站生成框架,它可以帮助我们快速构建高性能的网站。而 GraphQL 是一种查询语言,它可以帮助我们从数据源中获取我们所需的数据。在 Gatsby 中,我们可以使用 GraphQL 查询来获取 Markdown 文件的数据,并且可以通过文件夹过滤来获取特定文件夹下的数据。
现在,让我们来看看如何在 Gatsby 中使用 GraphQL 来按文件夹过滤allMarkdownRemark。首先,在你的 Gatsby 项目中,你需要安装 gatsby-source-filesystem 插件。你可以通过运行以下命令来安装:shellnpm install gatsby-source-filesystem然后,在你的
gatsby-config.JS 文件中,配置 gatsby-source-filesystem 插件。假设你的 Markdown 文件存放在 content 文件夹下,你可以这样配置:Javascriptmodule.exports = { plugins: [ { resolve: "gatsby-source-filesystem", options: { name: "content", path: <code>${__dirname}/content/</code>, }, }, ],};接下来,在你的页面组件中,你可以使用 GraphQL 查询来获取 Markdown 文件的数据。假设你想要获取 posts 文件夹下的所有 Markdown 文件的数据,你可以这样查询:JSximport React from "react";import { graphql } from "gatsby";export const query = graphql<code> query { allMarkdownRemark( filter: { fileABSolutePath: { RegEx: "/posts/" } } ) { edges { node { frontmatter { title date(formatString: "YYYY-MM-DD") } excerpt } } } }</code>;const MyPage = ({ data }) => { const posts = data.allMarkdownRemark.edges; // 在这里你可以使用获取到的数据进行渲染 // ... return <div>{/* 渲染内容 */}</div>;};export default MyPage;在上面的代码中,我们使用了 filter 参数来过滤 fileABSolutePath,只保留了路径中包含 "posts" 的 Markdown 文件。至此,我们已经学会了如何在 Gatsby 中使用 GraphQL 来按文件夹过滤 allMarkdownRemark 数据了。案例代码:JSximport React from "react";import { graphql } from "gatsby";export const query = graphql<code> query { allMarkdownRemark( filter: { fileABSolutePath: { RegEx: "/posts/" } } ) { edges { node { frontmatter { title date(formatString: "YYYY-MM-DD") } excerpt } } } }</code>;const MyPage = ({ data }) => { const posts = data.allMarkdownRemark.edges; return ( <div> <h1>我的博客文章</h1> {posts.map(({ node }) => ( <div key={node.frontmatter.title}> <h2><strong>{node.frontmatter.title}</strong></h2> {node.excerpt}
<img src="https://img.izhida.com/topic/d52387880e1ea22817a72d3759213819.jpg" alt="Java"><br>Java
发布日期:{node.frontmatter.date} </div> ))} </div> );};export default MyPage;以上是如何在 Gatsby 中按文件夹过滤 allMarkdownRemark 的方法,并附上了案例代码。希望这篇文章对你有所帮助!Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号