メタデータを追加するための準備
yarn add gatsby-plugin-react-helmet react-helmet
gatsby-config.jsにgatsby-plugin-react-helmet
の設定を追加する
gatsby-plugin-react-helmet
このプラグインを使って、タイトルやメタ属性などの属性をコンポーネントに追加すると、それらがGatsbyが構築する静的なHTMLページに追加されます。これはサイト閲覧者にとってだけでなく、SEOにとっても重要です。
react-helmet
headタグの管理をするコンポーネント
メタデータの設定を記述するファイルを準備
import React from "react";
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<html lang="言語の種類" />
<meta charSet="utf-8" />
<title>My Title</title>
<meta name="description" content="説明" />
<link rel="canonical" href="http://mysite.com/example" />
</Helmet>
...
</div>
);
}
};
サイト全体で使用するメタデータの値を用意する
サイト全体で繰り返し使用したいメタデータは、siteMetadataとして用意しておくとGraphQLのクエリで取得できるようになる
gatsby-config.js
module.exports = {
/* Your site config here */
siteMetadata: {
title: `Example`,
description: `Example description`,
lang: `ja`,
siteUrl: `https://*******.netlify.app`
},
plugins: [
...
ページごとにメタデータの値を変える
example.js
export default ({data}) => (
<Layout>
<SEO
pagetitle="example"
pagedesc="example description"
/>
<div>
...
参考文献:
Webサイト高速化のための静的サイトジェネレーター活用入門
react-helmet: https://github.com/nfl/react-helmet
gatsby-plugin-react-hemet: https://www.gatsbyjs.com/plugins/gatsby-plugin-react-helmet/