Created
March 14, 2018 02:42
-
-
Save 5t111111/afdfedd91f80e2cc79e5168801186c7b to your computer and use it in GitHub Desktop.
gatsbyでURLを `/YYYY/MM/DD/slug` という形式にする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
exports.onCreateNode = ({ node, getNode, boundActionCreators }) => { | |
const { createNodeField } = boundActionCreators; | |
if (node.internal.type === 'MarkdownRemark') { | |
// Create slug with post date directory structure | |
const createSlug = (postDate, filePath) => { | |
const year = postDate.getFullYear(); | |
const month = `0${postDate.getMonth() + 1}`.slice(-2); // month with zero padding | |
const date = `0${postDate.getDate()}`.slice(-2); // date with zero padding | |
return `/${year}/${month}/${date}/${filePath.replace(/^\/posts\//, '')}`; | |
}; | |
const date = new Date(node.frontmatter.date); | |
const filePath = createFilePath({ node, getNode }); | |
const slug = createSlug(date, filePath); | |
createNodeField({ | |
node, | |
name: 'slug', | |
value: slug, | |
}); | |
} | |
}; | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment