Skip to content

Instantly share code, notes, and snippets.

@5t111111
Created March 14, 2018 02:42
Show Gist options
  • Save 5t111111/a587e3b8344794f8f39b59015c832651 to your computer and use it in GitHub Desktop.
Save 5t111111/a587e3b8344794f8f39b59015c832651 to your computer and use it in GitHub Desktop.
gatsbyでURLを `/YYYY/MM/DD/slug` という形式にする
...
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