我是Gatsby的新手,并尽我最大的努力去学习它(以及React,我也没有先验知识)。我想创建一个页面,以从一个或多个markdown文件中获取数据。
目前,我仅使用Gatsby对其进行测试,以便以后使用Netlify CMS降价文件重现该技术(并能够使用Netlify CMS管理面板更新页面文本)。 到目前为止,由于这个tutorial,我已经设法向Marktsby添加了降价页面。但是这种方法只能创建动态页面,比我需要的页面复杂得多。
是否有一种简单的方法可以导入一个特定的markdown文件,比如在src / markdowns / hero-texts.md中(也可以说)在pages / index.js中,然后在它们的frontmatter标签中调用数据最干净的方法?
我已经在Google上进行了无数的研究,只是发现哪个插件或编码术语可以解决该问题,但没有成功。我完全理解了上面的某些解释,可能充满了技术误解,对此感到抱歉...
答案 0 :(得分:2)
您有一个名为hero-texts.md
的降价文件,并且希望能够查询其前题内容。
安装插件gatsby-transformer-remark
和gatsby-source-filesystem
,并设置gatsby-source-filesystem
选项以找到您的降价文件。
// gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown`,
path: `${__dirname}/src/markdowns/`
}
},
`gatsby-transformer-remark`
]
}
您可以在index.js
内进行诸如此类的graphql页面查询(然后查询结果将自动添加到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
}
}
}
`
它将从如下所示的降价文件中提取最重要的字段。
// 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)