gray-matter

Simple Key·2021년 12월 3일
1

gray-matter

마크다운 파일로 블로그를 만들경우 거의 필수로 사용되어지는 라이브러리.
스트링 또는 텍스트파일의 front-matter를 파싱해준다.

front matter가 있는 스트링을 변환

---
title: 타이틀
slug: main
---
<h1>컨텐츠</h1>

결과

{
  content: '<h1>컨텐츠</h1>',
  data: {
    title: '타이틀',
    slug: 'main'
  }
}

Nextjs, fs와 함께 사용하기 ?

// 임포트 해오기
import matter from 'gray-matter';


// ... 생략


export async function getStaticProps(){
  // 'posts' 디렉토리에서 파일 읽어오기
  const files = fs.readdirSync(path.join("posts"));
  // 리턴값 예
  //files = 1: [
  //'네번째-포스트.md',
  //'다섯번째-포스팅.md',
  //'두번째-포스트.md',
  //'세번째-포스트.md',
  //'여섯번째 포스팅.md',
  //'일곱번째-포스팅.md',
  //]
  
  const posts = files.map((filename) => {
    // 'posts' 디렉토리 내 파일에서 frontmatter 값 가져오기
  	const markdownWithMeta = fs.readFileSync(
	  path.join('posts', filename), 'utf-8'
    )
    
    // 가져온 frontmatter값을 gray-matter를 사용해 객체로 변환
    const { data: frontmatter } = matter(markdownWithMeta);
  })
  
  return { ...생략 }
}

file system 모듈로'posts' 디렉토리내 .md 파일들을 읽어드리고
각 .md 파일의 frontmatter를 가져와 matter 메서드로 객체 데이터로 변환 시켜줄 수 있다.

profile
프론트엔드 개발자 심기현 입니다.

0개의 댓글