Skip to content

Commit

Permalink
update slugs
Browse files Browse the repository at this point in the history
  • Loading branch information
elzup committed Jan 5, 2020
1 parent f261f96 commit 34505a0
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
title: Hexo と gh-pages でブログを作った
date: 2019-02-09 19:10:20
id: start-blog
tags:
- hexo
- GitHub Pages
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
title: akispace.fm をはじめました
date: 2019-03-04 11:28:00
id: build-radio
tags:
- yattecast
- github-pages
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
title: はやくもブログを Hexo から Gatsby に切り替えた
date: 2019-03-06 11:58:50
id: start-blog
tags:
- Gatsby
- React
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
title: Gatsby で Twitter 埋め込みする
date: 2019-03-12 20:47:00
id: gatsby-skill
tags:
- Gatsby
- GitHub Pages
Expand Down
27 changes: 27 additions & 0 deletions content/blog/2020/2020-01-04___gatsby-customize-slug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
title: GatsbyJSで記事のURLをカスタマイズする
date: 2020-01-04 23:03:38
tags:
- Gatsby
category:
- Tech
---

この記事では GatsbyJS で作るブログの **slug(URL のパス部分)** のカスタマイズ方法を紹介します。

## URL(記事のパス)の変更方法

(`gatsby-source-filesystem`)[https://www.gatsbyjs.org/packages/gatsby-source-filesystem/] を使用しています。

## 実装例

今回このブログを例にカスタマイズします。

プロジェクトのブログポストのディレクトリ構造はここに位置しています。
`/content/blog/{year}/{year}-{month}-{day}_{slug}.md`

変更前の記事 URL は以下で、
`https://blog.anozon.me/2020/2020-01-04_gatsby-customize-slug`

slug に当たる部分のみを URL に含める形にしたいです。
`https://blog.anozon.me/gatsby-customize-slug`
24 changes: 16 additions & 8 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

const SLUG_SEPARATOR = '___'

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

Expand Down Expand Up @@ -50,15 +52,21 @@ exports.createPages = ({ graphql, actions }) => {
})
}

const getSlug = path => {
const [prefix, slug] = path.split(SLUG_SEPARATOR)
return slug || path
}

exports.onCreateNode = ({ node, actions, getNode }) => {
if (node.internal.type !== `MarkdownRemark`) return

const { createNodeField } = actions
const filePath = createFilePath({ node, getNode, trailingSlash: false })
const slug = getSlug(filePath)

if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
createNodeField({
name: `slug`,
node,
value: slug,
})
}

0 comments on commit 34505a0

Please sign in to comment.