728x90
getStaticProps 구현
1️⃣ 먼저 각 마크다운 파일의 Meta-Data를 구문 분석 할 수 있는 gray-matter를 설치 합니다.
$ npm install gray-matter
2️⃣ 파일 시스템에서 데이터를 가져오기 위한 간단한 라이브러리를 만듭니다.
🥕 최상위 루트에 lib 디렉토리를 생성합니다.
🥕🥕 lib 디렉토리 내부에 posts.js라는 파일을 추가합니다.
(내부에 아래 코드를 삽입합니다.)
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
const postsDirectory = path.join(process.cwd(), 'posts')
export function getSortedPostsData() {
// Get file names under /posts
const fileNames = fs.readdirSync(postsDirectory)
const allPostsData = fileNames.map(fileName => {
// Remove ".md" from file name to get id
const id = fileName.replace(/\.md$/, '')
// Read markdown file as string
const fullPath = path.join(postsDirectory, fileName)
const fileContents = fs.readFileSync(fullPath, 'utf8')
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents)
// Combine the data with the id
return {
id,
...matterResult.data
}
})
// Sort posts by date
return allPostsData.sort(({ date: a }, { date: b }) => {
if (a < b) {
return 1
} else if (a > b) {
return -1
} else {
return 0
}
})
}
3️⃣ getSortedPostsData에 대한 import를 추가하고 pages/index.js의 getStaticProps 내에서 호출합니다.
4️⃣ 터미널을 열고 pages/index.js 내에 export Home 위에 다음 코드를 추가합니다.
import { getSortedPostsData } from '../lib/posts'
export async function getStaticProps() {
const allPostsData = getSortedPostsData()
return {
props: {
allPostsData
}
}
}
5️⃣ allPostsData 함수 내에 블로그 게시물이 구성 요소에 전달 됩니다.
이제 아래와 같이 블로그 게시물에 엑세스 할 수 있습니다.
6️⃣ 블로그 게시물을 표시하기 위해 Home 컴포넌트 내에 태그를 추가 해보겠습니다.
export default function Home({ allPostsData }) {
return (
<Layout home>
{/* Keep the existing code here */}
{/* Add this <section> tag below the existing <section> tag */}
<section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
<h2 className={utilStyles.headingLg}>Blog</h2>
<ul className={utilStyles.list}>
{allPostsData.map(({ id, date, title }) => (
<li className={utilStyles.listItem} key={id}>
{title}
<br />
{id}
<br />
{date}
</li>
))}
</ul>
</section>
</Layout>
)
}
7️⃣ yarn dev 또는 npm run dev로 개발 모드 실행 후 localhost:3000으로 액세스 해보면
파일 시스템에서 외부 데이터를 성공적으로 불러오고, 렌더링 한 걸 볼 수 있습니다.
728x90
'프레임워크 > Next.js' 카테고리의 다른 글
[Next.js] 동적 경로 (0) | 2022.02.20 |
---|---|
[Next.js] 요청 시 데이터 가져오기 (0) | 2022.02.18 |
[Next.js] 블로그 데이터 (0) | 2022.02.18 |
[Next.js] 데이터가 있거나 없는 정적 생성(SSG) (0) | 2022.02.18 |
[Next.js] 두 가지 형태의 사전 렌더링 (0) | 2022.02.18 |
댓글