Gatsby.js - OGP画像、Twitterカードの画像の設定
1. OGP 画像、Twitter カードの画像のメタタグやサイズなどの確認
Summary Card
<meta name="twitter:card" content="summary" />
- 最小サイズ: 144 x 144px
- 最大サイズ: 4096 x 4096px
- アスペクト比: 1 : 1
- 画像形式: JPG、PNG、WEBP、GIF
- 画像サイズ: 5MB 未満
Summary Card Large Image
<meta name="twitter:card" content="summary_large_image" />
- 最小サイズ: 300 x 157px
- 最大サイズ: 4096 x 4096px
- アスペクト比: 2 : 1
- 画像形式: JPG、PNG、WEBP、GIF
- 画像サイズ: 5MB 未満
Open Graph Image
<meta property="og:image" content="url" />
- 最小サイズ: 200 x 200px
- 高解像度で最適な表示: 1200 x 630px 以上
- アスペクト比: 1.91 : 1
- 画像サイズ: 8MB 未満
画像が 600 x 315 以下だと表示サイズが小さくなる(Twitter の Summary Card のような表示になる)
Open Graph タグのog:image:width
およびog:image:height
で画像サイズを指定しておくと表示処理が早くなる。
Summary with large image | Twitter Developer
リンクシェアの画像 - Facebook for Developers
2. OGP 画像、 Twitter カードの画像の設定
OGP 画像や Twitter カードの画像の設定は、記事に画像を使用していない場合は、画像を 1 枚用意しメタデータの設定をすれば表示されるようになります。ここでは、記事ごとに画像を使用していて 画像を動的に変更させる方法を書いておこうと思います。
マークダウンファイルで画像を使用するための設定
マークダウンファイルで画像を使用するためのプラグインをインストールします。
npm install gatsby-image gatsby-remark-images gatsby-transformer-sharp gatsby-plugin-sharp
yarn add gatsby-image gatsby-remark-images gatsby-transformer-sharp gatsby-plugin-sharp
インストール後、gatsby-config.js
でプラグインを追加と設定をします。
//gatsby-config.js
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 590,
},
},
],
},
},
記事ごとに画像を動的に変更させる
記事ごとの画像を下記のように設定していたとします。
---
title: article1
date: "2000-01-01"
category: "CatA"
tags: ["TagA"]
featuredImage: "./post-image.png"
---
画像を動的に変更させるためには画像のソースが必要なので、GraphQL で画像のソースを取得します。ここだとfeaturedImage
のsrc
が画像のソースになります。
export const pageQuery = graphql`
query BlogPostSlug($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
excerpt(pruneLength: 160)
frontmatter {
title
date(formatString: "YYYY/MM/DD")
category
tags
featuredImage {
childImageSharp {
resize(width: 1200) {
src
height
width
}
}
}
}
}
}
`
画像のソースを取得できたのでreact-helmet
でメタデータの設定を書き換えます。
<SEO
title={post.frontmatter.title}
description={post.excerpt}
pathname={location.pathname}
image={post.frontmatter.featuredImage.childImageSharp.resize.src}
/>
設定が完了したらCard validatorで記事ごとに画像が変更されるか確認をして変更されていれば完了です。
Search Engine Optimization (SEO) and Social Sharing Cards with Gatsby | Gatsby