Gatsby でプロジェクト作成

最近では、ホームページの作成に Gatsby というものを利用するのが流行っているようです。

Gatsby のサイトによると、「Gatsbyとは一言でいうと、爆速なサイトを手軽に構築するためのReact製のフレームワークです。」とのことです。

Gatsby のインストールとプロジェクト作成

gatsby-cli のインストール。


yarn global add gatsby-cli

プロジェクト作成。


yarn create gatsby my-gatsby-site

サーバー起動。


cd ~/my-gatsby-site
yarn start

http://localhost:8000/ にアクセス。

構造を理解する

Gatsby であっという間に、プロジェクトが作成されページができましたが、上の場合は ~/my-gatsby-site/src/pages/index.js が少し複雑過ぎて今の段階では動きが理解できません。

そこでもっとわかりやすいサンプルはないかと検索したところ、qiita のこのページがとてもいい感じでした。

まず、いろいろなファイル・ディレクトリを作成します。


mkdir ~/my-gatsby-site/src/components
touch ~/my-gatsby-site/src/components/header.js
touch ~/my-gatsby-site/src/components/footer.js
touch ~/my-gatsby-site/src/components/layout.js
touch ~/my-gatsby-site/src/pages/second.js

構造は、


~/my-gatsby-site
├── gatsby-config.js
├── package.json
├── src
│   ├── components
│   │   ├── footer.js
│   │   ├── header.js
│   │   └── layout.js
│   ├── images
│   │   └── icon.png
│   └── pages
│       ├── 404.js
│       ├── index.js
│       └── second.js
└── yarn.lock
~/my-gatsby-site/src/componets/footer.js

import React from "react"

export default () => (
  <footer>
    <small>サンプルサイトのフッター!</small>
  </footer>
)
~/my-gatsby-site/src/componets/header.js

import React from "react"

export default () => (
  <header>
    <h1>サンプルサイトのヘッダー!</h1>
  </header>
)
~/my-gatsby-site/src/componets/layout.js

import React from "react"
import Header from "../components/header"
import Footer from "../components/footer"

export default ({ children }) => (
  <> {/* <React.Fragment>の省略形 */}
    <Header />
    {children}
    <Footer />
  </>
)
~/my-gatsby-site/src/pages/second.js

import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"

export default () => (
  <Layout>
    <div>
      <p>2つ目のページのメインコンテンツ!</p>
      <Link to={"/"}>トップページへのリンク</Link>
    </div>
  </Layout>
)
~/my-gatsby-site/src/pages/index.js

import React from "react"
import { Link } from "gatsby" //追加
import Layout from "../components/layout"

export default () => (
  <Layout>
    <div>
      <p>トップページのメインコンテンツ!</p>
      <Link to={"/second/"}>Secondページへのリンク</Link> {/* 追加 */}
    </div>
  </Layout>
)

サーバー起動。


cd ~/my-gatsby-site
yarn start

これはすごい。
なるほどこうやるんですね。