为 Gatsby Contentful 博客文章修改 URL

Modify URL for Gatsby Contentful blog posts

我最近将 Contentful 与我的 Gatsby 网站集成在一起,一切都运行良好。 我有最后一期关于我博客 post 页面的 slugs/URLs。

目前这些的 URL 类似于 http://localhost:8000/blog/another-blog-post 但我希望它们是 http://localhost:8000/blog/year/another-blog-post年份是根据它们的发布日期创建的。

在我的 gatsby-node.js 文件中我有以下内容

if (posts.length > 0) {
    posts.forEach((post, index) => {
      const previousPostId = post.previous?.id 
      const nextPostId = post.next?.id 
      const postYear = new Date(post.node.publishDate).getFullYear();

      createPage({
        path: `/blog/${post.node.slug}`,
        component: blogPost,
        context: {
          id: post.id,
          previousPostId,
          nextPostId,
          slug: post.node.slug
        },
      })
    })
  }

在那个例子中 post.node.slug 是 'another-blog-post' 我创建了 postYear 变量,它正确地给出了它们发布的年份。
我认为 link 对于那些 post 的 <Link className="button" aria-label={Read ${title}} to={/blog/${post.slug}} itemProp="url">

我不知道如何让 URL 实际包含年份。

我确实尝试更改 pathslugto= 以包含 ${postYear},但这会导致 404。

我设法解决了我自己的问题,不是 100% 确定这是否是最好的方法,但它似乎工作得很好。
我将路径更新为 path: /blog/${postYear}/${post.node.slug} 然后用

链接到它
const postUrl = `/blog/${post.postYear}/${post.slug}`
<Link className="button" aria-label={`Read ${title}`} to={postUrl} itemProp="url">

经过多年测试,似乎符合我的预期。