gatsby - 如何更改 Gatsby 博客文章页面的生成路径?

标签 gatsby

默认情况下,我的 Gatsby 网址类似于 2018-09-06-hexagon
有什么办法可以让他们变成/blog/2018/09/06/hexagon ?

这是我的 gatsby-node.js 的相关部分文件:

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  return new Promise((resolve, reject) => {
    const blogPost = path.resolve('./src/templates/blog-post.js')
    resolve(
      graphql(
        `
          {
            allMarkdownRemark(
              sort: { fields: [frontmatter___date], order: DESC }
              limit: 1000
            ) {
              edges {
                node {
                  fields {
                    slug
                  }
                  frontmatter {
                    title
                  }
                }
              }
            }
          }
        `
      ).then(result => {
        if (result.errors) {
          console.log(result.errors)
          reject(result.errors)
        }


        // Create blog posts pages.
        const posts = result.data.allMarkdownRemark.edges


        _.each(posts, (post, index) => {
          const previous =
            index === posts.length - 1 ? null : posts[index + 1].node
          const next = index === 0 ? null : posts[index - 1].node


          createPage({
            path: post.node.fields.slug,
            component: blogPost,
            context: {
              slug: post.node.fields.slug,
              previous,
              next,
            },
          })
        })
      })
    )
  })
}

最佳答案

您可以更新博客文章 frontmatter 中的 slug 以在您想要的位置包含斜杠,或者您可以转换 createPages 中的 slug。 :

        // Create blog posts pages.
        const posts = result.data.allMarkdownRemark.edges

        _.each(posts, (post, index) => {
          const previous =
            index === posts.length - 1 ? null : posts[index + 1].node
          const next = index === 0 ? null : posts[index - 1].node
          const blogPostPath = 
            `/blog/${post.node.fields.slug.replace(/-/g, "/")}`

          createPage({
            path: blogPostPath,
            component: blogPost,
            context: {
              slug: post.node.fields.slug,
              postPath: blogPostPath,
              previous,
              next,
            },
          })
        })

关于gatsby - 如何更改 Gatsby 博客文章页面的生成路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655149/

相关文章:

caching - Gatsby 图片在 iPad 上无法按需要缓存

javascript - 以编程方式从 API 数据创建 Gatsby 页面

reactjs - 在《 Gatsby 》中将 Prop 从布局传递给 child

Twitter 卡片图像不适用于 Gatsby 应用程序

javascript - 准备要传递到 API 查询的字符串(转义特殊字符)

gatsby - GitHub 操作失败,出现 Gatsby 错误 : Input file contains unsupported image format

javascript - 根据 slider 中的不同子项计算正确的 div 高度?

javascript - 使用不同的模板在 gatsby 中创建页面

reactjs - 如何在 gatsby 网站中实现 Google Ad Manager(又名 DFP)?

git - 致命的 : A branch named 'gh-pages' already exists