コンテンツにスキップ

19

シンプルなブログアーキテクチャの作成

この例のブログ記事は、アプリケーションのディレクトリ内のローカルマークダウンファイルとして保存されます(外部データソースから取得されるわけではありません)。そのため、ファイルシステムからデータを読み取る必要があります。

このセクションでは、ファイルシステムからマークダウンデータを読み取るブログを作成する手順を説明します。

マークダウンファイルの作成

まず、ルートフォルダに **posts** という名前の新しいトップレベルディレクトリを作成します(これは pages/posts とは異なります)。posts ディレクトリ内に、**pre-rendering.md** と **ssg-ssr.md** の2つのファイルを作成します。

次に、以下のコードを posts/pre-rendering.md にコピーします。

---
title: 'Two Forms of Pre-rendering'
date: '2020-01-01'
---
 
Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page.
 
- **Static Generation** is the pre-rendering method that generates the HTML at **build time**. The pre-rendered HTML is then _reused_ on each request.
- **Server-side Rendering** is the pre-rendering method that generates the HTML on **each request**.
 
Importantly, Next.js lets you **choose** which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.

次に、以下のコードを posts/ssg-ssr.md にコピーします。

---
title: 'When to Use Static Generation v.s. Server-side Rendering'
date: '2020-01-02'
---
 
We recommend using **Static Generation** (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.
 
You can use Static Generation for many types of pages, including:
 
- Marketing pages
- Blog posts
- E-commerce product listings
- Help and documentation
 
You should ask yourself: "Can I pre-render this page **ahead** of a user's request?" If the answer is yes, then you should choose Static Generation.
 
On the other hand, Static Generation is **not** a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.
 
In that case, you can use **Server-Side Rendering**. It will be slower, but the pre-rendered page will always be up-to-date. Or you can skip pre-rendering and use client-side JavaScript to populate data.

各マークダウンファイルの上部には、titledate を含むメタデータセクションがあることに気づいたかもしれません。これは YAML Front Matter と呼ばれ、gray-matter というライブラリを使用して解析できます。

gray-matter のインストール

まず、各マークダウンファイルのメタデータを解析できるようにする gray-matter をインストールします。

npm install gray-matter

ファイルシステムから読み取るためのユーティリティ関数の作成

次に、ファイルシステムからデータを解析するためのユーティリティ関数を作成します。このユーティリティ関数を使用して、以下を行います。

  • 各マークダウンファイルを解析し、titledate、およびファイル名(投稿URLのidとして使用されます)を取得します。
  • インデックスページにデータを、日付でソートして一覧表示します。

ルートディレクトリに 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((a, b) => {
    if (a.date < b.date) {
      return 1;
    } else {
      return -1;
    }
  });
}

注意

Next.js を学習するために上記のコードが何をしているかを理解する必要はありません。この関数は、ブログの例を機能させるためのものです。しかし、さらに学習したい場合は、

  • fs は、ファイルシステムからファイルを読み取ることを可能にするNode.jsモジュールです。
  • path は、ファイルパスを操作することを可能にするNode.jsモジュールです。
  • matter は、各マークダウンファイルのメタデータを解析することを可能にするライブラリです。
  • Next.js では、lib フォルダには pages フォルダのような割り当てられた名前はありません。そのため、任意の名前を付けることができます。一般的には lib または utils が慣習です。

ブログデータの取得

ブログデータが解析されたので、これをインデックスページ(pages/index.js)に追加する必要があります。これは、Next.js のデータ取得メソッドである getStaticProps() を使用して行うことができます。次のセクションでは、getStaticProps() の実装方法を学びます。

Index Page

次のページでやりましょう!

チャプターを完了しました。19

次へ

20: 事前レンダリングとデータ取得