前回のおさらい
React.js の component を使って Blog などを生成できる Gatsby という Node.js 製の Statice site generator を紹介しました。 Markdown だけでなく JSON ファイルのようなデータ構造からも静的ファイルを生成する事ができるので今回はそのやり方を紹介します。
ちなみに、v1.3 を試していたらすでに v1.5 になっていました。タイトルどうしよう。
準備
プロジェクトを作成する
gatsby new practice-gatsby-json && cd $_
Source plugin を追加する
nodes 生成時に必要なデータをファイルから読み込む為のプラグインを追加する。
yarn add gatsby-source-filesystem
gatsby-config.js を修正し、プラグインを設定します。
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
},
- plugins: [`gatsby-plugin-react-helmet`],
+ plugins: [
+ `gatsby-plugin-react-helmet`,
+ {
+ resolve: `gatsby-source-filesystem`,
+ options: {
+ path: `${__dirname}/src/pages`,
+ name: 'pages',
+ },
+ }
+ ],
}
Transformer plugins を追加する
nodes 生成時に JSON 形式から変換させるプラグインを追加する
yarn add gatsby-transformer-json
gatsby-config.js を修正し、プラグインを設定します。
path: `${__dirname}/src/pages`,
name: 'pages',
},
- }
+ },
+ `gatsby-transformer-json`,
],
}
json ファイルを用意
jsonplaceholder のデータをお借りします。以下のような json ファイルを src/pages/posts.json として保存します。
[
{
"id": "1",
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"id": "2",
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
動作確認
yarn develop
http://localhost:8000/___graphql を開いて以下のクエリを実行します。
一覧取得
{
allPostsJson {
edges {
node {
id
title
body
}
}
}
}

詳細取得
query {
postsJson(id: {eq: "1"}) {
id
title
body
}
}

まとめ
というわけで JSON ファイルから nodes を生成する方法を紹介しました。gatsby@1.0.0 以降から nodes を生成するのに markdown 以外の方法が増えたので gatsby の可能性に私はとても期待しています。
次回は http で外部API を fetch して、そこから nodes を生成する方法を紹介します。