如何更改Gatsby博客帖子页面的生成路径?

时间:2018-10-04 21:06:11

标签: 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,
            },
          })
        })
      })
    )
  })
}

1 个答案:

答案 0 :(得分:2)

您可以更新博客文章的前题中的子句以在需要的地方包含斜杠,也可以在createPages内转换该子句:

        // 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,
            },
          })
        })