Gatsby + Markdown:如何将特定 Markdown 文件中的数据放入单个页面?

Flo*_*noy 8 markdown reactjs gatsby

我是 Gatsby 的新手,正在尽我所能地学习它(还有 React,我也没有任何先验知识)。我想创建一个页面,从一个或多个 Markdown 文件中获取数据。

现在,我只使用 Gatsby 对其进行测试,以便稍后使用 Netlify CMS 降价文件重现该技术(并且能够使用 Netlify CMS 管理面板更新页面文本)。到目前为止,由于本教程,我已经成功地向 Gatsby 添加了降价页面。但是这种方法只创建动态页面,这比我需要的要复杂得多。

有没有一种简单的方法可以导入一个特定的 Markdown 文件,比如说 src/markdowns/hero-texts.md,在(也可以说)pages/index.js 中,然后用它们的 frontmatter 标签调用数据,以最干净的方式作为可能的?

我在谷歌上尝试了无数研究,只是为了找到哪个插件或编码术语可以处理这个问题,但没有成功。我完全明白上面的一些解释可能充满了技术误解,抱歉......

ksa*_*sav 9

您有一个名为hero-texts.mdMarkdown 的文件,并且您希望能够查询其 frontmatter 内容。

安装插件gatsby-transformer-remarkgatsby-source-filesystem设置gatsby-source-filesystem选项以查找 Markdown 文件。


// gatsby-config.js

module.exports = {
    plugins: [
        {
        resolve: `gatsby-source-filesystem`,
            options: {
              name: `markdown`,
              path: `${__dirname}/src/markdowns/`
            }
        },
        `gatsby-transformer-remark`
    ]
}
Run Code Online (Sandbox Code Playgroud)

您可以在里面进行这样的graphql页面查询index.js(然后查询的结果会自动添加到您的索引组件下props.data

// src/pages/index.js

import React from "react"
import { graphql } from "gatsby"

const IndexPage = ({data}) => {
  return (
  <>
    <p>{data.markdownRemark.frontmatter.author}</p>
    <p>{data.markdownRemark.frontmatter.date}</p>
    <p>{data.markdownRemark.frontmatter.title}</p>
  </>
)}

export default IndexPage

export const pageQuery = graphql`
  query IndexPageQuery {
    markdownRemark(fileAbsolutePath: { regex: "/hero-texts.md/" }) {
      frontmatter {
        author
        date
        title
      }
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

它将在构建时执行 graphql 查询,并将查询结果添加到页面组件的dataprop 中IndexPage

所以实际上,从一个看起来像这样的降价文件中提取所有 frontmatter 字段。

// src/markdowns/hero-texts.md

---
title: "Gatsby + Markdown: How to simply get data from a specific markdown in a single page?"
author: Florent Despinoy
date: 2019-08-06
---

# This is my markdown post

The content of this markdown file would not be queried by pageQuery (only the frontmatter would)
Run Code Online (Sandbox Code Playgroud)