もがき系プログラマの日常

もがき系エンジニアの勉強したこと、日常のこと、気になっている技術、備忘録などを紹介するブログです。

GatsbyJSさわってみた

はじめに

こんばんは。今回は積本消化月間 vol.1で手を進みながら勉強した、GatsbyJSをやってみたログ的なものをきれいに整形してブログにしました。

WEB+DB PRESS Vol.108

WEB+DB PRESS Vol.108

  • 作者: 中野暁人,山本浩平,大和田純,曽根壮大,ZOZOTOWNリプレースチーム,権守健嗣,茨木暢仁,松井菜穂子,新多真琴,laiso,豊田啓介,藤原俊一郎,牧大輔,向井咲人,大島一将,上川慶,末永恭正,久保田祐史,星北斗,池田拓司,竹馬光太郎,粕谷大輔,WEB+DB PRESS編集部
  • 出版社/メーカー: 技術評論社
  • 発売日: 2018/12/22
  • メディア: 単行本
  • この商品を含むブログを見る

GastbyJSは、自分が所属しているWriteBlogEveryWeekに、Contributorの @mottox2 さんが同じく所属しており、以前少し話題が出たときに気になってましたので、ちょうどよかったですw

twitter.com

今回はやってみたログなので、プログラムコードに関しては、本で紹介されている内容を忠実に再現しています。

本題

1. GatsbyJS CLIの準備と初期設定

インストール
$ yarn global add gatsby-cli
.
..
...
✨  Done in 70.60s.
インストール確認
$ gatsby --version
Gatsby has started collecting anonymous usage analytics to help improve Gatsby for all users.
If you'd like to opt-out, you can use `gatsby telemetry --disable`
To learn more, checkout http://gatsby.dev/telemetry
2.5.6

本では、バージョンが2.4.4でしたがバージョンが上がって2.5.6が入りました。 また、妙なメッセージが出たので何だと調べると、Gastbyが、改善などのために情報を集めますみたいな話のようです。 情報を送信したくない場合は gatsby telemetry --disable を実行しなさいとうことだそうです。

こちらのメッセージは二回目以降は出なくなりました。

スターターキットをインストール
$ gatsby new gatsby_test https://github.com/gatsbyjs/gatsby-starter-hello-world
info Creating new site from git: https://github.com/gatsbyjs/gatsby-starter-hello-world.git
Cloning into 'gatsby_test'...
remote: Enumerating objects: 547, done.
remote: Total 547 (delta 0), reused 0 (delta 0), pack-reused 547
Receiving objects: 100% (547/547), 1.72 MiB | 486.00 KiB/s, done.
Resolving deltas: 100% (355/355), done.
success Created starter directory layout
info Installing packages...
yarn install v1.12.3
warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning "gatsby > eslint-plugin-graphql@2.1.1" has incorrect peer dependency "graphql@^0.12.0 || ^0.13.0".
warning "gatsby > express-graphql@0.6.12" has incorrect peer dependency "graphql@^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0".
warning "gatsby > graphql-tools@3.1.1" has incorrect peer dependency "graphql@^0.13.0".
warning "gatsby > pnp-webpack-plugin > ts-pnp@1.0.1" has unmet peer dependency "typescript@*".
[4/4] 📃  Building fresh packages...
✨  Done in 191.23s.
info Initialising git in gatsby_test
Initialized empty Git repository in /path/to/gatsby_test/.git/
info Create initial git commit in gatsby_test
テストプロジェクトインストール確認
$ cd gatsby_test
$ ll
total 1712
-rw-r--r--     1 kojirock  staff   1.0K  4 10 00:46 LICENSE
-rw-r--r--     1 kojirock  staff   5.2K  4 10 00:46 README.md
drwxr-xr-x  1000 kojirock  staff    31K  4 10 00:49 node_modules
-rw-r--r--     1 kojirock  staff   452K  4 10 00:46 package-lock.json
-rw-r--r--     1 kojirock  staff   770B  4 10 00:46 package.json
drwxr-xr-x     3 kojirock  staff    96B  4 10 00:46 src
drwxr-xr-x     3 kojirock  staff    96B  4 10 00:46 static
-rw-r--r--     1 kojirock  staff   382K  4 10 00:46 yarn.lock
立ち上げて実行確認
$ gatsby develop
success open and validate gatsby-configs — 0.007 s
success load plugins — 0.044 s
success onPreInit — 0.007 s
success initialize cache — 0.006 s
success copy gatsby files — 0.131 s
success onPreBootstrap — 0.016 s
success source and transform nodes — 0.014 s
success building schema — 0.122 s
success createPages — 0.000 s
success createPagesStatefully — 0.049 s
success onPreExtractQueries — 0.000 s
success update schema — 0.026 s
success extract queries from components — 0.014 s
success run graphql queries — 0.011 s — 2/2 211.74 queries/second
success write out page data — 0.005 s
success write out redirect data — 0.001 s
success onPostBootstrap — 0.000 s

info bootstrap finished - 5.132 s

 DONE  Compiled successfully in 4274ms                                                                                                                                                                                                                                                                                00:52:35


You can now view gatsby-starter-hello-world in the browser.

  http://localhost:8000/

View GraphiQL, an in-browser IDE, to explore your site's data and schema

  http://localhost:8000/___graphql

Note that the development build is not optimized.
To create a production build, use npm run build

ℹ 「wdm」: 
ℹ 「wdm」: Compiled successfully.

f:id:kojirooooocks:20190410021551p:plain

f:id:kojirooooocks:20190410021605p:plain

起動できました。

http://localhost:8000/___graphql というURLも表示されたのですが、こちらはGatsbyJSで使用されているGraphQLのURLです。

2. ページ追加 & 修正

aboutページを作成
// src/pages/about.js 

import React from "react"
export default () => <div>aboutページ</div>

f:id:kojirooooocks:20190410021617p:plain

問題なく表示されました。

componentsを追加
// src/components/Header.js 

import React from 'react';
export default props => <h1 style={{ color: `red` }}>{props.title}</h1>
componentを各ページで使用
// src/page/index.js 

import React from "react"
import { Link } from 'gatsby'
import Header from '../components/Header'
export default () => (
  <div>
    <Link to="/about/">about</Link>
    <Header title="トップページ"/>
  </div>
);
// src/page/about.js 

import React from "react"
import { Link } from 'gatsby'
import Header from '../components/Header'

export default () => (
  <div>
    <Link to="/">top</Link>
    <Header title="aboutページ"/>
  </div>
);

f:id:kojirooooocks:20190410021632p:plain

f:id:kojirooooocks:20190410021643p:plain

propsもcssも動いてます。

本で紹介されている CSS-in-JSという方法も試してみます。

CSS-in-JSのためのライブラリインストール
$ yarn add gatsby-plugin-emotion emotion emotion-server react-emotion @emotion/core
.
..
...
....
.....
✨  Done in 18.36s.

本で紹介されているインストールでは @emotion/core をインストールするということは書いてなかったのですが、現バージョンだとエラーが出てしまったので、 @emotion/core をインストールするようにしました。

gatsby-config.jsを作成
// gatsby-config.js 

module.exports = {
  plugins: [
    `gatsby-plugin-emotion`
  ]
}
componentsを修正
// src/components/Header.js 

import React from 'react';
import { css } from 'emotion';
const style = css({
  color: 'blue'
});
export default props => <h1 className={style}>{props.title}</h1>

f:id:kojirooooocks:20190410021658p:plain

f:id:kojirooooocks:20190410021709p:plain

問題なくスタイルが適用されました!

3. GraphQLを使用してみる

プラグインをインストール
$ yarn add gatsby-source-filesystem gatsby-transformer-remark
.
..
✨  Done in 13.13s.
gatsby-config.jsを修正
// gatsby-config.js

module.exports = {
  plugins: [
    `gatsby-plugin-emotion`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },
    `gatsby-transformer-remark`
  ]
}
markdownを作成
// src/md/blog.md

---
title: 'ブログタイトル'
date: '2019-04-10'
---
ブログの記事内容です。
GraphQLページで記入して確認
{
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          title
          date
        }
        excerpt
        timeToRead
        html
      }
    }
  }
}

f:id:kojirooooocks:20190410021725p:plain

先ほど入れたpluginがうまく動いてくれているようです。

  • gatsby-source-filesystem

    => ソースからデータを取得する

  • gatsby-transformer-remark

    => 読み込んだmarkdownデータを加工してGraphQLデータとして扱う

Markdownファイルのデータを使用してページに反映する
// src/pages/index.js

import React from "react"
import { graphql, Link } from 'gatsby'
import Header from '../components/Header'

export default ({data}) => (
  <div>
    <Header title="トップページ" />
    <Link to="/about/">about</Link>
    {data.allMarkdownRemark.edges.map(({node}) => (
      <div key={node.id}>
        <h3>
          {node.frontmatter.title}
          <span>
            {node.frontmatter.date}
          </span>
        </h3>
        <p>{node.excerpt}</p>
      </div>
    ))}
  </div>
);

export const query = graphql`
  query {
    allMarkdownRemark {
      totalCount
      edges {
        node {
          id
          frontmatter {
            title
            date(formatString: "DD MMMM, YYYY")
          }
          excerpt
        }
      }
    }
  }
`;

f:id:kojirooooocks:20190410021739p:plain

GraphQL初めて使いましたが、自分はあまり有効なイメージが湧きませんでした。

もうちょっと勉強します。。。

終わりに

チュートリアルとかも見たことない自分でもとてもわかり易く試しやすい記事でした。

また本書では、更に、PWAサポートや、Netlifyで公開する対応なども親切に記載されていました。

興味がある人は是非一読ください。

更に、最初に紹介させてもらった @mottox2さんのブログにもGatsbyJSについての情報が多くありますので、ぜひ一度御覧ください。

mottox2.com

簡単でしたが今回はここまでです。