Post Image

Generate Route with fs and markdown.

Author Image

Published 19th Sep 2022 by James Aspinall

TLDR;

  1. Pages are dynamically generated by mapping through the filesystem of the contents directory. Children files with in are used to generate the second part of the route. gray-matter and react-markdown are used to parse the yaml with in the *.md files and render the styled markdown on the pages.
  2. To add more pages add a new *.md file to the required Area of Focus ensuring that the correct metadata is added to the top of the file.

packages

nodes fs allows us to use the structure of the contents folder to generate our staticPaths and staticProps. The initial dynamic route for used for the “Area of Focus” is acquired by mapping through the parent folder and getting the names of the child directories i.e. assessments, carer, communication etc. The second part of the route is acquired by mapping through the child directories and getting the names of the child files i.e. assessment.md, carer.md, communication.md etc. The names of the files are used to generate the second part of the route. The names of the files are also used to generate the staticProps for the pages.

1export async function getStaticPaths() { 2 const paths = fs 3 .readdirSync(`${process.cwd()}/contents`) 4 .map((area) => { 5 const files = fs.readdirSync(`${process.cwd()}/contents/${area}`); 6 return files.map((file) => ({ 7 params: { 8 area: area, 9 page: file.replace('.md', ''), 10 }, 11 })); 12 }) 13 .flat(); 14 return { 15 paths, 16 fallback: false, 17 }; 18} 19

The staticProps are generated by reading the file using fs and parsing the yaml with grey-matter. The markdown is then rendered using react-markdown.

1export async function getStaticProps({ params }) { 2 const { area, page } = params; 3 const markdownWithMeta = fs.readFileSync( 4 `${process.cwd()}/contents/${area}/${page}.md`, 5 'utf-8' 6 ); 7 const { data: frontmatter, content } = matter(markdownWithMeta); 8 return { 9 props: { 10 frontmatter, 11 content, 12 }, 13 }; 14} 15

Example *.md file

1--- 2title: "Title Of Article" 3date: "2022-09-19" 4exerpt: "Short bit" 5description: "Longer short bit" 6tags: 7 - Tag 1 8 - Tag 2 9--- 10 11# Assessment 12Quis culpa duis dolor aliquip ullamco velit ipsum exercitation ea. Sunt ex aliqua non nostrud consequat consequat deserunt irure sint labore est quis. Qui duis qui id et aliqua do commodo deserunt do. 13 14Veniam ad anim tempor ex occaecat velit duis pariatur cillum. Amet ut sit non consectetur aute minim voluptate eiusmod. Ex adipisicing ipsum velit irure. In exercitation non fugiat nisi minim commodo veniam eu. Dolor veniam duis non Lorem Lorem Lorem. 15## Assessment 16 17### Assessment 18
#nextJS#getStaicProps#getStaticPaths#routes#markdown