og:image
用画像を生成するGatsbyプラグインを作りました。Qiitaの記事がTwitterでシェアされるときに使われる画像みたいなのを簡単に作れます。こういうのですね。

https://github.com/akr4/gatsby-plugin-og-image
実はこのブログは最近Gatsbyに移行していて、このプラグインを使っているので自動生成したog:image
が設定されています。
使い方
この画像の元となるHTMLを返す関数を定義しておいて、
const renderOgImage = ({ title }) => {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body style="
padding: 0;
margin: 0;
">
<div style="
width: 1200px;
height: 590px;
background-color: #292D3F;
color: #F1F0EE;
display: flex;
flex-direction: column;
justify-content: center;
border-bottom: 40px solid #6D757F;
">
<div style="font-family: sans-serif; font-size: 60px; font-weight: bold; margin: 0 40px;">${title}</div>
<div style="font-family: serif; font-size: 48px; margin: 160px 40px 0 auto;">example.com</div>
</div>
</body>
</html>
`;
};
gatsby-node.js
でcreatePage
するときにコンテキストのogImagePlugin
以下に先ほどの関数の引数として渡す値を設定します。
createPage({
path: '/my-first-page',
component: blogPost,
context: {
ogImagePlugin: {
title: 'My first page',
},
},
});
つまりcreatePage
の段階で取得できる任意の値をHTML生成関数に渡せるので、作成できる画像の自由度は高いでしょう。
SSRの時とクライアント側でルーティングした時の両方でHTMLの<meta property="og:image">
タグが更新されます。