【问题标题】:How to define Gatsby markdown page paths in one file?如何在一个文件中定义 Gatsby markdown 页面路径?
【发布时间】:2018-11-14 11:17:36
【问题描述】:

默认情况下,Gatsby 使用 frontmatter 定义路径,例如:

---
path: /example-page
---

然后通过 GraphQL 使用它。

为所有markdown文件定义这些路径的最佳方法是什么,不是在每个文件中写入frontmatter部分,而是在一个文件中,例如,像这样:

[
    {
        "title": "Example",
        "path": "/example-page.md"
    }
]

【问题讨论】:

    标签: graphql gatsby static-site


    【解决方案1】:

    您可以通过在创建页面时添加路径来做到这一点。

    将此添加到gatsby-node

    const { createFilePath } = require(`gatsby-source-filesystem`);
    
    exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
    
      const { createNodeField } = boundActionCreators
    
      if (node.internal.type === `MarkdownRemark`) {
    
        const slug = createFilePath({
          node,
          getNode,
          basePath: `pages`
        })
    
        createNodeField({
          node,
          name: `slug`,
          value: `/pages${slug}`
        })
    
      }
    
    };
    

    createFilePathpages目录下的markdown文件转成/pages/slug

    createNodeField 创建名为“slug”的新可查询字段。

    现在在graphql,您可以访问 slug:

    {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
    

    然后您可以像往常一样使用新的 slug 字段作为页面路径来创建页面。

    这样,您可以在 graphql 中可访问的数据中添加您的标题和所有您想要的内容。

    此处示例:https://www.gatsbyjs.org/tutorial/part-seven/

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 2019-12-08
      • 2021-10-13
      • 2017-01-25
      • 1970-01-01
      • 2021-08-29
      • 2020-04-16
      • 2015-07-13
      • 2023-03-17
      相关资源
      最近更新 更多