エンジニアを目指す日常ブログ

日々勉強したことのメモ。独学ですので間違っていたらコメント等で教えてください。

Gatsbyブログでのプラグイン利用方法/画像の挿入方法

はじめに

Gatsbyプラグインを導入する方法をメモする。 絶対に必要になる、画像挿入のためのプラグインgatsby-plugin-imageを導入してみる。

参照したサイト:
www.gatsbyjs.com

この記事のゴール

  • Gatsbyでのプラグイン利用方法を理解する。
  • gatsby-plugin-imageを利用して静的画像を挿入する。

前回の記事

tomiko0404.hatenablog.com

パッケージの利用方法

おおまかな流れは以下。

  1. 目的のパッケージと、その依存関係にあるパッケージをnpm installする
  2. gatsby-config.jsプラグイン設定を追記する
  3. インポートして呼び出す

有名なプラグインgatsby-plugin-image

インストールの実施

インストール方法は、以下のようなプラグインの説明サイトを見て確認する。インストール用コマンドが記載されている。 www.gatsbyjs.com

依存関係のあるパッケージがあるので、同時にインストールする必要がある。 例えば、gatsby-plugin-image

を同時にインストールする必要がある。

ただし、gatsby-starter-blogスターターキットには既にプラグインが入っている(package.jsonに入っているので、gatsby newした段階でnpm installされている)ので改めて行う必要は無さそう。

以下コマンドを実施してみたところ、package.jsonの該当パッケージのバージョンが最新に更新された。

$  npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem

gatsby-config.jsへの追記

インストールした依存パッケージ全てを記載する必要は無いらしい。その説明も、プラグイン説明ページに記載されている。

スターターキットを利用しているので、私の環境では既に以下の記載がされていた。他のプラグインの記載もあった。

gatsby-config.js

module.exports = {
    ・・・(省略)・・・
    plugins: [
      `gatsby-plugin-image`,
      `gatsby-transformer-sharp`,
      `gatsby-plugin-sharp`,
      ・・・(省略)・・・,
    ],
  }

プラグインの利用

以下の文でインポートして、<StaticImage>コンポーネントを利用できる。

import { StaticImage } from 'gatsby-plugin-image'

index.jsでインポートした上で、以下記載を追加した。

src/pages/index.jsreturn文の中身

      {/* 画像を追加(src/images/から) */}
      <StaticImage
        alt="Gatsbyブログ勉強中の画像"
        src="../images/gatsbyブログの概要-Page-1.jpg"
      />

      {/* 画像を追加(APIから) */}
      <StaticImage
        alt="Gatsbyブログ勉強中の画像"
        src="https://source.unsplash.com/rPOmLGwai2w"
      /> 

参考:gatsby-config.jsについて

プラグインの管理や、メタデータの設定などを行なう。 ルートフォルダに置く必要がある。

参考:gatsby-config.jsの説明 Gatsby Config API | Gatsby

gatsby-config.jsはホットリロード対象にならないようなので、開発時に本ファイルを変更した際は再度gatsby developする必要があるとのこと。

gatsby-config.jsはモジュールを切り出したファイル

以下記事でまとめた通り、Node.jsでは

module.exports = () => {};

のように、module.exportsに関数や変数を代入すると、モジュールとして呼び出すこととができるようになる。

tomiko0404.hatenablog.com

gatsby-config.jsの記載は以下のようになっており、オブジェクトをモジュール化していることがわかる。

module.exports = {
  siteMetadata: {
      //省略
  },
  plugins: [
      //省略

  ],
}

このモジュールはGatsby側で自動で読み込まれる。

index.js全文

import * as React from "react"
import { Link, graphql } from "gatsby"

import Bio from "../components/bio"
import Layout from "../components/layout"
import Seo from "../components/seo"

import { StaticImage } from "gatsby-plugin-image"

const BlogIndex = ({ data, location }) => {
  const siteTitle = data.site.siteMetadata?.title || `Title`
  const posts = data.allMarkdownRemark.nodes


  if (posts.length === 0) {
    return (
      <Layout location={location} title={siteTitle}>
        <Seo title="All posts" />
        <Bio />
        <p>
          No blog posts found. Add markdown posts to "content/blog" (or the
          directory you specified for the "gatsby-source-filesystem" plugin in
          gatsby-config.js).
        </p>
      </Layout>
    )
  }

  return (
    <Layout location={location} title={siteTitle}>
      <Seo title="All posts" />
      <Bio />


      {/* Aboutページを追加*/}
      <Link to="/about">このサイトについて</Link>

      {/* 画像を追加(src/images/から) */}
      <StaticImage
        alt="Gatsbyブログ勉強中の画像"
        src="../images/gatsbyブログの概要-Page-1.jpg"
      />

      {/* 画像を追加(APIから) */}
      <StaticImage
        alt="Gatsbyブログ勉強中の画像"
        src="https://source.unsplash.com/rPOmLGwai2w"
      />      

      <ol style={{ listStyle: `none` }}>
        {posts.map(post => {
          const title = post.frontmatter.title || post.fields.slug

          return (
            <li key={post.fields.slug}>
              <article
                className="post-list-item"
                itemScope
                itemType="http://schema.org/Article"
              >
                <header>
                  <h2>
                    <Link to={post.fields.slug} itemProp="url">
                      <span itemProp="headline">{title}</span>
                    </Link>
                  </h2>
                  <small>{post.frontmatter.date}</small>
                </header>
                <section>
                  <p
                    dangerouslySetInnerHTML={{
                      __html: post.frontmatter.description || post.excerpt,
                    }}
                    itemProp="description"
                  />
                </section>
              </article>
            </li>
          )
        })}
      </ol>
    </Layout>
  )
}

export default BlogIndex

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      nodes {
        excerpt
        fields {
          slug
        }
        frontmatter {
          date(formatString: "MMMM DD, YYYY")
          title
          description
        }
      }
    }
  }
`

参考:適当な画像を持ってくるサイト

Unsplashというサイトから画像を借用することができる。APIで持ってこられるので便利。

https://source.unsplash.com/{画像のID}

にアクセスすると、画像データを取得できる。

unsplash.com

使い方の説明は以下のサイトがとてもわかりやすい。

bagelee.com