コンテンツをスキップ

19

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

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

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

Markdownファイルの作成

まず、ルートフォルダにpostsという新しいトップレベルディレクトリを作成します(これはpages/postsとは異なります)。posts内に、pre-rendering.mdssg-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.

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

gray-matterのインストール

まず、各Markdownファイルのメタデータを解析できるgray-matterをインストールします。

npm install gray-matter

ファイルシステムを読み込むユーティリティ関数の作成

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

  • 各Markdownファイルを解析し、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は、各Markdownファイルのメタデータを解析できるライブラリです。
  • Next.jsでは、libフォルダにはpagesフォルダのように割り当てられた名前がないため、自由に名前を付けることができます。通常、libまたはutilsを使用するのが慣例です。

ブログデータの取得

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

Index Page

次のページで実行しましょう!

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

次へ

20: プリレンダリングとデータフェッチング