差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン 前のリビジョン
次のリビジョン
前のリビジョン
javascript:gatsby [2021/08/03 18:52] – 削除 techwikijavascript:gatsby [2022/04/05 17:24] (現在) techwiki
行 1: 行 1:
 +====== Gatsby.js ======
  
 +===== Gatsby.jsのプロジェクトを作成する方法 =====
 +<code bash>
 +gatsby new xxx https://github.com/gatsbyjs/gatsby-starter-blog
 +</code>
 +
 +''xxx''という名前のプロジェクトを作成。
 +(''xxx''というディレクトリが作成される)
 +
 +''スターター''として、''%%https://github.com/gatsbyjs/gatsby-starter-blog%%''のようなURLを指定する。
 +
 +----
 +[[https://www.gatsbyjs.com/starters|Gatsby.js公式・Gatsby Starters]]から、好みのスターターを検索できる。
 +
 +1番人気の''gatsby-starter-blog''はスター数が''3000''程度。
 +2番人気の''gatsby-starter-netlify-cms''はスター数が''1800''程度。
 +
 +初心者は''gatsby-starter-blog''を使ったほうがいい。
 +チュートリアルは''gatsby-starter-blog''がベースとなっているので学習しやすい。
 +カスタマイズのための情報も多い。
 +
 +=====Gatsby.jsサービスのURLとポートを変更する方法=====
 +====デフォルトのURLとポート(develop)====
 +<code bash>
 +npm run develop
 +</code>
 +Gatsby.jsでWebサイトを作成後、
 +''npm run develop''
 +のコマンドでWebサービスが起動する。
 +
 +ブラウザに
 +''%%http://localhost:8000%%''
 +というURLを入力すると、Gatsby.jsで作成したサイトが表示される。
 +
 +
 +====デフォルトのURLとポート(production)====
 +<code bash>
 +npm run build
 +npm run serve
 +</code>
 +''npm run build''
 +でプロジェクトをビルド後、
 +''npm run serve''
 +のコマンドでWebサービスが起動する。
 +
 +ブラウザに
 +''%%http://localhost:9000%%''
 +というURLを入力すると、Gatsby.jsで作成したサイトが表示される。
 +
 +====Gatsby.jsサービスのホストを設定====
 +デフォルトの設定では、
 +''%%http://localhost:8000%%''のようなURLでアクセスできるが
 +''%%http://192.168.1.1:8000%%''のようなURLではアクセスできない。
 +(IPアドレス指定でページを表示できない)
 +
 +そのため、コマンドを実行した端末上からしかアクセスできない。
 +スマホで表示が確認できないため、レスポンシブが機能しているか確認しづらい。
 +
 +サービスの起動オプションにhostを設定することで、IPアドレスでのアクセスを可能にする。
 +
 +----
 +
 +''npm run develop''や''npm run serve''の実態は、
 +''package.json''に定義されている。
 +
 +<code - package.json抜粋>
 +{
 +    "scripts": {
 +        "develop": "gatsby develop",
 +        "serve": "gatsby serve",
 +    }
 +}
 +</code>
 +上記の部分を、下記のように変更。
 +<code - package.json抜粋>
 +{
 +    "scripts": {
 +        "develop": "gatsby develop -H=0.0.0.0",
 +        "serve": "gatsby serve -H=0.0.0.0",
 +    }
 +}
 +</code>
 +
 +''-H=0.0.0.0''オプションを指定することで、
 +''%%http://192.168.1.1:8000%%''
 +のようなURLでサイトを表示できるようになる。
 +
 +IPアドレスは、''npm run develop''や''npm run serve''コマンドを実行したホストのもの。
 +
 +''-H=0.0.0.0''の部分は、
 +''-H 0.0.0.0''(イコールなし)や
 +''--host=0.0.0.0''でもOK。
 +
 +====Gatsby.jsサービスのポートを設定====
 +<code - package.json抜粋>
 +{
 +    "scripts": {
 +        "develop": "gatsby develop -H=0.0.0.0 -p=8001",
 +        "serve": "gatsby serve -H=0.0.0.0 -p=9002",
 +    }
 +}
 +</code>
 +
 +''-p''オプションを指定することで、
 +デフォルトの''8000''や''9000''以外のポートでサービスを起動する。
 +
 +Gatsby.jsで複数のサイトを起動したとき、デフォルトのポートのままでは競合するので、ポートの変更が必須となる。
 +
 +=====Gatsby.jsから不要なプラグインを削除する=====
 +不要なプラグインなどは削除した方が全体のファイルサイズが小さくなり、ビルド時間の短縮になる。
 +====prismjsをアンインストール====
 +''prismjs''は、ソースコードをシンタックスハイライトするためのプラグイン。
 +
 +Gatsby.jsのサイトでソースコードを表示させないなら不要。
 +
 +<code bash>
 +npm uninstall prismjs
 +npm uninstall gatsby-remark-prismjs
 +</code>
 +
 +''prismjs''本体と、
 +''prismjs''をmarkdownで扱うためのプラグイン(''gatsby-remark-prismjs'')をアンインストール。
 +
 +----
 +===prismjs関連の設定を削除===
 +==gatsby-config.js==
 +''gatsby-config.js''ファイルの''plugins''の項目から下記の部分を削除。
 +<code javascript gatsby-config.js>
 +`gatsby-remark-prismjs`,
 +</code>
 +
 +
 +----------
 +==gatsby-browser.js==
 +''gatsby-browser.js''ファイルから下記の部分を削除。
 +<code javascript gatsby-browser.js>
 +import "prismjs/themes/prism.css"
 +</code>
 +
 +
 +====gatsby-plugin-google-analyticsをアンインストール====
 +''gatsby-plugin-google-analytics''は、Gatsby.jsでGoogle Analyticsを設定するためのプラグイン。
 +
 +Google Tag Managerを通してGoogle Analyticsを利用するので
 +直接Google Analyticsを扱う''gatsby-plugin-google-analytics''は不要。
 +
 +<code>
 +npm uninstall gatsby-plugin-google-analytics
 +</code>
 +
 +----
 +===gatsby-plugin-google-analytics関連の設定を削除===
 +''gatsby-config.js''の''plugins''の項目から以下を削除。
 +
 +<code javascript gatsby-config.js>
 +// {
 +//   resolve: `gatsby-plugin-google-analytics`,
 +//   options: {
 +//     trackingId: `ADD YOUR TRACKING ID HERE`,
 +//   },
 +// },
 +</code>
 +
 +元々コメントアウトされているので、消さなくても影響はない。
 +しかし、''gatsby-plugin-google-analytics''を使わない場合は、完全に不要な設定なので削除した方が分かりやすい。
 +
 +====不要なフォントをアンインストール====
 +<code bash>
 +npm uninstall typeface-merriweather
 +npm uninstall typeface-montserrat
 +</code>
 +
 +----
 +===フォント関連の設定を削除===
 +''gatsby-browser.js''から下記の部分を削除。
 +
 +<code javascript gatsby-browser.js>
 +// custom typefaces
 +import "typeface-montserrat"
 +import "typeface-merriweather"
 +</code>
 +
 +=====グローバルcssを削除する方法=====
 +====グローバルcssの設定を削除====
 +''gatsby-browser.js''から下記の部分を削除。
 +<code javascript gatsby-browser.js>
 +// normalize CSS across browsers
 +import "./src/normalize.css"
 +// custom CSS styles
 +import "./src/style.css"
 +</code>
 +
 +====グローバルcssのファイルを削除====
 +下記のファイルを削除
 +  * ./src/normalize.css
 +  * ./src/style.css
 +
 +=====MuiThemeProviderを作成する方法=====
 +グローバルcssを削除した代わりに、
 +Material UIの''ThemeProvider''でcssを管理する。
 +
 +====material-ui関連のプラグインをインストール====
 +<code bash>
 +npm install @material-ui/core
 +npm install gatsby-plugin-material-ui
 +</code>
 +
 +''material-ui''の本体と、
 +''material-ui''をgatsbyで利用するためのプラグインをインストール。
 +
 +====material-ui関連の設定====
 +''gatsby-config.js''の''plugins''に下記を追加。
 +<code javascript gatsby-config.js抜粋>
 +"gatsby-plugin-material-ui",
 +</code>
 +
 +====MuiThemeProviderコンポーネントを作成====
 +''src/components''ディレクトリに''MuiThemeProvider.jsx''というファイルを新規作成。
 +
 +<code javascript MuiThemeProvider.jsx>
 +import React from "react"
 +import { CssBaseline } from "@material-ui/core"
 +import {
 +  ThemeProvider,
 +  createMuiTheme,
 +  responsiveFontSizes,
 +} from "@material-ui/core/styles"
 +
 +const MuiThemeProvider = ({ children }) => {
 +  let theme = createMuiTheme({
 +    // 背景色を適用すると、cssが適用される前に一瞬白背景が映るので画面がちらつく
 +    // palette: {
 +    //   background: {
 +    //     default: "#dddddd",
 +    //   },
 +    // },
 +    // フォントを適用すると、最初にブラウザのデフォルトフォントで表示され、
 +    // 一瞬後にここで指定したフォントに切り替わるので画面がちらつく
 +    // typography: {
 +    //   fontFamily: ["Noto Serif", "Noto Sans JP"].join(","),
 +    // },
 +  })
 +  theme = responsiveFontSizes(theme)
 +
 +  return (
 +    <ThemeProvider theme={theme}>
 +      <CssBaseline />
 +      {children}
 +    </ThemeProvider>
 +  )
 +}
 +export default MuiThemeProvider
 +</code>
 +
 +''createMuiTheme''を使って背景色やフォントなどを指定できる。
 +
 +''responsiveFontSizes''フォントサイズをレスポンシブ対応できる。
 +
 +''CssBaseline''により、最低限のcssを適用した状態になる。
 +
 +残りは各コンポーネント単位で、''makeStyles''を使ってcssを適用していく。
 +
 +====MuiThemeProviderコンポーネントを適用====
 +''gatsby-browser.js''に下記を追加。
 +<code javascript gatsby-browser.js抜粋>
 +import React from "react"
 +import MuiThemeProvider from "./src/components/MuiThemeProvider"
 +export const wrapRootElement = ({ element }) => {
 +  return <MuiThemeProvider>{element}</MuiThemeProvider>
 +}
 +</code>
 +
 +''wrapRootElement''の中で''MuiThemeProvider''を適用することで、全体ページにスタイルが適用される。
 +
 +=====dotenvで環境変数を設定する方法=====
 +dotenvを使うと、開発環境と本番環境などステージ別で環境変数を定義することができる。
 +
 +====dotenvをインストール====
 +<code bash>
 +npm install dotenv
 +</code>
 +
 +====.envファイルを作成====
 +プロジェクトのルートディレクトリに下記の2つのファイルを作成する。
 +  * .env.development
 +  * .env.production
 +
 +''.env.development''には、開発環境用の環境変数を、
 +''.env.production''には、本番環境用の環境変数を書く。
 +
 +====.gitignoreに.envの除外設定を追加====
 +<code>
 +.env*
 +</code>
 +
 +''.env.development''と''.env.production''をgitの管理対象外とする。
 +
 +一般的に、''.env''系のファイルではデータベースのパスワードなどの機密事項を管理する。
 +そのため、Githubなどにアップロードしてはならない。
 +
 +
 +
 +
 +====.envをインポート====
 +''gatsby-confi.js''の先頭付近に下記を記載。
 +
 +<code javascript gatsby-confi.js>
 +const fs = require("fs")
 +const envPath = `.env.${process.env.NODE_ENV}`
 +if (fs.existsSync(envPath)) {
 +  require("dotenv").config({
 +    path: envPath,
 +  })
 +}
 +</code>
 +
 +''npm run develop''コマンド実行時には、''process.env.NODE_ENV''に''development ''という文字列が入る。
 +よって、''require("dotenv")''では''.env.development''が読み込まれる。
 +
 +''npm run build''コマンド実行時には、''process.env.NODE_ENV''に''production ''という文字列が入る。
 +よって、''require("dotenv")''では''.env.production ''が読み込まれる。
 +
 +Gatsby Cloudなどのホスティングサービスにデプロイするときは、
 +git対象管理外の''.env.production''のデータは読み込まれない。
 +
 +そのため、ホスティングサービスに備え付けの管理画面から環境変数を別途設定する。
 +
 +=====Gatsby.jsでサイトマップを作成する方法=====
 +====gatsby-plugin-sitemapをインストール====
 +<code>
 +npm install gatsby-plugin-sitemap
 +</code>
 +sitemap生成用のプラグインをインストール。
 +
 +====gatsby-plugin-sitemapを設定====
 +''gatsby-config.js''の''plugins''に下記を追加。
 +<code javascript gatsby-config.js抜粋>
 +    {
 +      resolve: "gatsby-plugin-sitemap",
 +      options: {
 +        output: "/",
 +      },
 +    },
 +</code>
 +
 +====npm run buildを実行====
 +<code bash>
 +npm run build
 +</code>
 +ビルドのタイミングで、''public''ディレクトリ直下に
 +  * sitemap-0.xml
 +  * sitemap-index.xml
 +というファイルが作成される。
 +
 +====gatsby-plugin-sitemapのバグ====
 +''gatsby-config.js''への設定で、
 +''output: "/",''を指定しなかった場合はバグが発生する。
 +(2021年7月現在)
 +
 +''output: "/",''を指定しないと
 +''public/''ディレクトリではなく
 +''public/sitemap/''ディレクトリに
 +''sitemap-0.xml''と''sitemap-index.xml''が作成される。
 +
 +しかし、''/sitemap/sitemap-index.xml''からの内部リンクで
 +''/sitemap/sitemap-0.xml''になるべきところが
 +''/sitemap-0.xml''になってしまう。
 +
 +''/sitemap-0.xml''は404エラーになるので、サイトマップとして機能しない。
 +
 +====Google Search Consoleにサイトマップを登録する====
 +[[/google:searchconsole|Google Search Consoleの使い方]]を参考に、
 +サイトマップとして''sitemap-index.xml''を登録する。
 +
 +''sitemap-index.xml''を登録すれば、''sitemap-0.xml''は連動してGoogleに認識される。
 +
 +=====Gatsby.jsにcanonicalを設定する方法=====
 +''canonial''とは、Googleなどの検索エンジンに正規のURLをお知らせする機能。
 +
 +''%%http://example.com%%''
 +''%%http://www.example.com%%''の両方のURLでサイトにアクセスできるようなとき、
 +どちらが正規のURLかを宣言する。
 +
 +====gatsby-plugin-canonical-urlsをインストール====
 +<code bash>
 +npm install gatsby-plugin-canonical-urls
 +</code>
 +
 +canonical設定用のプラグインをインストール。
 +
 +====gatsby-plugin-canonical-urlsを設定====
 +''gatsby-config.js''の''plugins''に以下を追加。
 +<code javascript gatsby-config.js抜粋>
 +    {
 +      resolve: `gatsby-plugin-canonical-urls`,
 +      options: {
 +        siteUrl: process.env.SITE_URL,
 +        stripQueryString: true,
 +      },
 +    },
 +</code>
 +
 +''SITE_URL''は環境変数。
 +開発環境と本番環境でURLが変わるので、環境変数で管理する。
 +
 +====gatsby-plugin-canonical-urlsで追加されるタグ====
 +''gatsby-plugin-canonical-urls''の効果により、
 +htmlの''head''タグに
 +''%%<link rel="canonical" href="http://example.com">%%''
 +のようなタグが追加される。
 +
 +=====Gatsby.jsにOGPを設定する方法=====
 +====react-helmetプラグインをインストール====
 +<code bash>
 +npm install react-helmet
 +npm install gatsby-plugin-react-helmet
 +</code>
 +
 +''react-helmet''本体と、
 +''react-helmet''をGatsby.jsで扱うためのプラグイン(''gatsby-plugin-react-helmet'')をインストール。
 +
 +====react-helmetプラグインを設定====
 +''gatsby-config.js''の''plugins''に以下を追加。
 +<code javascript gatsby-config.js>
 +    "gatsby-plugin-react-helmet",
 +</code>
 +
 +====react-helmetでheadにmetaタグを追加する方法====
 +''Seo.jsx''というコンポーネントを作成。
 +
 +<code javascript Seo.jsx>
 +import React from "react"
 +import { Helmet } from "react-helmet"
 +
 +const Seo = ({location}) => {
 +  // helmetに渡すメタデータ
 +  let metaDatas = [
 +    // OGPの設定、全ページ共通
 +    {
 +      property: "og:site_name",
 +      content: "xxxxx",
 +    },
 +    {
 +      property: "og:locale",
 +      content: "ja",
 +    },
 +    {
 +      name: "twitter:site",
 +      content: "xxxxx",
 +    },
 +    {
 +      name: "twitter:creator",
 +      content: "xxxxx",
 +    },
 +    {
 +      name: "twitter:card",
 +      content: "summary_large_image",
 +    },
 +
 +    // OGPの設定、ページごとに異なる部分
 +    {
 +      property: "og:type",
 +      content: "article",
 +    },
 +    {
 +      property: "og:url",
 +      content: "xxxxx",
 +    },
 +    {
 +      property: "og:title",
 +      content: "xxxxx",
 +    },
 +    {
 +      property: "og:description",
 +      content: "xxxxx",
 +    },
 +    {
 +      property: "og:image",
 +      content: "xxxxx",
 +    },
 +
 +    // OGP以外のメタデータ
 +    {
 +      name: "description",
 +      content: "xxxxx",
 +    },
 +  ]
 +
 +  return (
 +    <Helmet
 +      htmlAttributes={{
 +        lang: "ja",
 +        prefix: "og: http://ogp.me/ns#",
 +      }}
 +      title="xxxxx"
 +      meta={metaDatas}
 +    >
 +    </Helmet>
 +  )
 +}
 +export default Seo
 +</code>
 +
 +''xxxxx''の部分は各自の環境に合わせて文字列を設定する。
 +
 +----
 +<code javascript Seo.js抜粋>
 +    <Helmet
 +      htmlAttributes={{
 +        lang: "ja",
 +        prefix: "og: http://ogp.me/ns#",
 +      }}
 +    >
 +    </Helmet>
 +</code>
 +の部分の効果により、htmlのソースに
 +''%%<html lang="ja" prefix="og: http://ogp.me/ns#" data-react-helmet="lang,prefix">%%''
 +のようなタグが出力される。
 +
 +----
 +<code javascript Seo.js抜粋>
 +    <Helmet
 +      title="xxxxx"
 +    >
 +    </Helmet>
 +</code>
 +の部分の効果により、htmlソースの''head''タグ内に
 +''<title>xxxxx</title>''
 +のようなタグが出力される。
 +
 +----
 +<code javascript Seo.js抜粋>
 +    <Helmet
 +      meta={metaDatas}
 +    >
 +    </Helmet>
 +</code>
 +の部分の効果により、htmlソースの''head''タグ内に
 +''
 +<meta data-react-helmet="true" property="og:site_name" content="xxxxx">
 +<meta data-react-helmet="true" property="og:locale" content="ja">
 +<meta data-react-helmet="true" name="twitter:site" content="xxxxx">
 +<meta data-react-helmet="true" name="twitter:creator" content="xxxxx">
 +<meta data-react-helmet="true" name="twitter:card" content="summary_large_image">
 +<meta data-react-helmet="true" property="og:type" content="article">
 +<meta data-react-helmet="true" property="og:url" content="xxxxx">
 +<meta data-react-helmet="true" property="og:title" content="xxxxx">
 +<meta data-react-helmet="true" property="og:description" content="xxxxx">
 +<meta data-react-helmet="true" property="og:image" content="xxxxx">
 +<meta data-react-helmet="true" name="description" content="xxxxx">
 +''
 +のようなタグが出力される。
 +
 +
 +=====gatsbyjs.ioから独自ドメインへリダイレクトする方法=====
 +Gatsby.jsで作成したプロジェクトをGatsby Cloudへデプロイすると、
 +''%%http://xxx.gatsbyjs.io%%''
 +のようなURLが割り当てられる。
 +
 +Gatsby Cloudでは独自ドメインの設定が可能。
 +''example.com''というドメインを割り当てたと仮定する。
 +
 +このとき、
 +''%%http://xxx.gatsbyjs.io%%''
 +''%%http://example.com%%''の両方でページが表示できてしまう。
 +
 +Gatsby Cloudには301リダイレクトの機能がないので
 +''%%http://xxx.gatsbyjs.io%%''から
 +''%%http://example.com%%''へ''meta refresh''で転送する。
 +
 +つまり、
 +''%%<meta http-equiv="refresh" content="0;URL=https://example.com">%%''
 +のようなタグを生成する。
 +
 +----
 +
 +<code javascript Seo.jsx>
 +import React, { useState, useEffect } from "react"
 +import { Helmet } from "react-helmet"
 +
 +const Seo = ({location}) => {
 +  const [refreshContent, setRefreshContent] = useState()
 +
 +  useEffect(() => {
 +    if (location.host.endsWith("gatsbyjs.io")) {
 +      const urlRedirect = `http://example.com${location.pathname}${location.search}`
 +
 +      setRefreshContent(`0;URL="${urlRedirect}"`)
 +    } else {
 +      setRefreshContent(undefined)
 +    }
 +  }, [location])
 +
 +  let metaDatas = [
 +    {
 +      property: "og:site_name",
 +      content: "xxxxx",
 +    },
 +    {
 +      property: "og:locale",
 +      content: "ja",
 +    },
 +    中略
 +  ]
 +
 +  if (refreshContent !== undefined) {
 +    metaDatas = metaDatas.concat([
 +      {
 +        "http-equiv": "refresh",
 +        content: refreshContent,
 +      },
 +    ])
 +  }
 +
 +  return (
 +    <Helmet
 +      htmlAttributes={{
 +        lang: "ja",
 +        prefix: "og: http://ogp.me/ns#",
 +      }}
 +      title="xxxxx"
 +      meta={metaDatas}
 +    >
 +    </Helmet>
 +  )
 +}
 +export default Seo
 +</code>
 +
 +----
 +<code javascript Seo.jsx抜粋>
 +    if (location.host.endsWith("gatsbyjs.io")) {
 +      const urlRedirect = `http://example.com${location.pathname}${location.search}`
 + 
 +      setRefreshContent(`0;URL="${urlRedirect}"`)
 +    }
 +</code>
 +
 +元のURLが
 +''%%http://xxx.gatsbyjs.io/aaa/bbb?ccc=ddd%%''だったら、
 +''${location.pathname}''は、''/aaa/bbb''
 +''${location.search}''は、''?ccc=ddd''のような値が格納されている。
 +
 +''location.host''(ドメイン名)の末尾が''gatsbyjs.io''のときだけ、
 +''%%0;URL="http://example.com/aaa/bbb?ccc=ddd"%%''のような文字列を生成、stateに値を保存(setRefreshContent)している。
 +
 +''location.host''の値は、''useEffect''の中でのみ有効。
 +''useEffect''の外では''undefined''になるので注意。
 +
 +----
 +<code javascript Seo.jsx抜粋>
 +  if (refreshContent !== undefined) {
 +    metaDatas = metaDatas.concat([
 +      {
 +        "http-equiv": "refresh",
 +        content: refreshContent,
 +      },
 +    ])
 +  }
 +</code>
 +
 +''%%<meta http-equiv="refresh" content="0;URL=https://example.com">%%''
 +のようなタグを出力するために、''Helmet''に渡す値を設定している。
 +
 +元々のURLが''example.com''ドメインの場合は、
 +''refreshContent''の値が''undefined''なので、
 +''<meta http-equiv="refresh">''のタグは生成されない。
 +=====Gatsby.jsにGoogle Analyticsを設定する方法=====
 +====Google Analyticsでの作業====
 +[[google:analytics|Google Analytics]]で、''測定ID''を発行する。
 +
 +''測定ID''は、''Google Tag Manager''で''コンテナID''を発行するときに必要。
 +
 +====Google Tag Managerでの作業====
 +===コンテナIDを発行===
 +[[google:tagmanager|Google Tag Manager]]で、''<head>''タグ用コードを発行する。
 +
 +''<head>''タグ用コードの''GTM-XXXXXXX''の部分(''コンテナID'')だけを使う。
 +
 +<code>
 +<!-- Google Tag Manager -->
 +<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
 +new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
 +j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
 +'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
 +})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
 +<!-- End Google Tag Manager -->
 +</code>
 +のようなコード自体は、プラグインが自動的に挿入してくれるので、自分で設定は不要。
 +
 +----
 +
 +===gatsby-route-change トリガーを作成===
 +
 +''gatsby''や''react''ではページ遷移が普通のサイトとは違う。
 +URLを疑似的に変更して、変更のあるDOMだけを再描画している。
 +この疑似的なページ移動を計測するために専用のトリガー設定が必要。
 +
 +----
 +''コンテナ''を選択。
 +
 +----
 +''トリガー''を選択。
 +
 +''新規''をクリック。
 +----
 +''トリガーの設定''をクリック。
 +
 +''トリガーのタイプを選択'': ''カスタム イベント''
 +''イベント名'': ''gatsby-route-change''
 +
 +''保存''をクリック。
 +
 +----
 +
 +''トリガー名'': ''gatsby-route-change''
 +
 +''保存''をクリック。
 +
 +----
 +''タグ''を選択。
 +
 +''Google アナリティクス GA4 設定''をクリック。
 +
 +----
 +''トリガー''をクリック。
 +
 +''+''アイコンをクリック。
 +
 +''トリガーの選択'': ''gatsby-route-change''
 +
 +''配信トリガー''に、''All Pages''と''gatsby-route-change''が表示されていることを確認。
 +
 +''保存''をクリック。
 +
 +----
 +''公開''をクリック。
 +
 +====ローカルでの作業====
 +===GTM用プラグインをインストール===
 +<code bash>
 +npm install gatsby-plugin-google-tagmanager
 +</code>
 +
 +''gatsby-plugin-google-tagmanager''をインストール。
 +
 +----
 +===環境変数を設定(.env)===
 +''.env''ファイルに、
 +''GTM_CONTAINER_ID=GTM-XXXXXXX''
 +を追加。
 +
 +----
 +===環境変数を設定(Gatsby Colud)===
 +[[https://www.gatsbyjs.com/dashboard|Gatsby Cloud]]へアクセス。
 +
 +----
 +サイトを選択。
 +
 +----
 +''Site Settings''タブで、''Edit Variables''を選択。
 +
 +----
 +
 +''Key'': ''GTM_CONTAINER_ID''
 +''Value'':  ''GTM-XXXXXXX''
 +
 +''Save''をクリック。
 +
 +----
 +===gatsby-config.jsを編集===
 +''gatsby-config.js''の''plugins''に以下を追加。
 +
 +<code>
 +    {
 +      resolve: `gatsby-plugin-google-tagmanager`,
 +      options: {
 +        id: process.env.GTM_CONTAINER_ID,
 +        includeInDevelopment: false,
 +        defaultDataLayer: { platform: "gatsby" },
 +        routeChangeEventName: "gatsby-route-change",
 +      },
 +    },
 +</code>
 +
 +''process.env.GTM_CONTAINER_ID''の部分は、環境変数から読み込ませる値。
 +
 +''routeChangeEventName''の''gatsby-route-change''は、
 +[[google:tagmanager|Google Tag Manager]]でコンテナ作成時に、イベントトリガーの''イベント名''に設定した値。
 +
 +=====Gatsby.jsにGoogle AdSenseを導入する方法=====
 +====Google AdSenseでの作業====
 +[[google:adsense|Google AdSense解説]]を参考に、
 +  - Google AdSenseにサブドメインを追加
 +  - Google AdSenseの自動広告用のコードを取得
 +  - ディスプレイ広告を作成・広告コードを取得
 +  - 関連コンテンツを作成・広告コードを取得
 +
 +====ローカルでの作業====
 +===html.jsを作成===
 +プロジェクトの''.cache''ディレクトリにある''default-html.js''ファイルをコピーして、
 +''src''ディレクトリに''html.js''というファイルを作成する。
 +
 +----
 +''<head>''タグの末尾に''自動広告用のコード''を追加する。
 +
 +<code javascript html.js>
 +import React from "react"
 +import PropTypes from "prop-types"
 +
 +export default function HTML(props) {
 +  return (
 +    <html {...props.htmlAttributes}>
 +      <head>
 +        <meta charSet="utf-8" />
 +        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
 +        <meta
 +          name="viewport"
 +          content="width=device-width, initial-scale=1, shrink-to-fit=no"
 +        />
 +        {props.headComponents}
 +
 +        {process.env.GATSBY_FLAG_ADSENSE === "on" && (
 +          <script
 +            data-ad-client="ca-pub-1234567890123456"
 +            async
 +            src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
 +          ></script>
 +        )}
 +      </head>
 +      <body {...props.bodyAttributes}>
 +        {props.preBodyComponents}
 +        <div
 +          key={`body`}
 +          id="___gatsby"
 +          dangerouslySetInnerHTML={{ __html: props.body }}
 +        />
 +        {props.postBodyComponents}
 +      </body>
 +    </html>
 +  )
 +}
 +
 +HTML.propTypes = {
 +  htmlAttributes: PropTypes.object,
 +  headComponents: PropTypes.array,
 +  bodyAttributes: PropTypes.object,
 +  preBodyComponents: PropTypes.array,
 +  body: PropTypes.string,
 +  postBodyComponents: PropTypes.array,
 +}
 +</code>
 +
 +----
 +追加した部分だけ抜粋。
 +
 +<code javascript html.js>
 +        {process.env.GATSBY_FLAG_ADSENSE === "on" && (
 +          <script
 +            data-ad-client="ca-pub-1234567890123456"
 +            async
 +            src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
 +          ></script>
 +        )}
 +</code>
 +
 +''process.env.GATSBY_FLAG_ADSENSE === "on" &&''により、
 +環境変数''GATSBY_FLAG_ADSENSE''が''on''のときだけ、広告が表示されるようにしている。
 +
 +開発環境では''GATSBY_FLAG_ADSENSE''を''off''にしておき、
 +本番環境だけ''GATSBY_FLAG_ADSENSE''を''on''にする。
 +----
 +
 +===AdsenseMain.jsxを作成===
 +''src/components''ディレクトリに、''AdsenseMain.jsx''ファイルを新規作成。
 +
 +<code javascript AdsenseMain.jsx>
 +import React, { useEffect } from "react"
 +
 +const AdsenseMain = ({ path }) => {
 +  useEffect(() => {
 +    if (window) {
 +      window.adsbygoogle = window.adsbygoogle || []
 +      window.adsbygoogle.push({})
 +    }
 +  }, [path])
 +
 +  return (
 +    <ins
 +      className="adsbygoogle"
 +      style={{ display: "block" }}
 +      data-ad-client="ca-pub-1234567890123456"
 +      data-ad-slot="1234567890"
 +      data-ad-format="auto"
 +      data-full-width-responsive="true"
 +    ></ins>
 +  )
 +}
 +export default AdsenseMain
 +</code>
 +
 +''return''には、''ディスプレイ広告''のコードから''<ins></ins>''の部分だけを書いている。
 +
 +<code javascript>
 +  useEffect(() => {
 +    if (window) {
 +      window.adsbygoogle = window.adsbygoogle || []
 +      window.adsbygoogle.push({})
 +    }
 +  }, [path])
 +</code>
 +上記の部分が、広告コードの
 +''<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>''
 +に相当する。
 +
 +''useEffect''を使い、''location.path''が変更した時に(ページが遷移した時に)広告が更新されるようにしている。
 +
 +コンポーネントの引数''path''は、親コンポーネントから''location.path''を受け取っている。
 +
 +----
 +
 +===AdsenseMatched.jsxを作成===
 +''src/components''ディレクトリに、''AdsenseMatched.jsx''ファイルを新規作成。
 +
 +<code javascript AdsenseMatched.jsx>
 +import React, { useEffect } from "react"
 +
 +const AdsenseMatched = ({ path }) => {
 +  useEffect(() => {
 +    if (window) {
 +      window.adsbygoogle = window.adsbygoogle || []
 +      window.adsbygoogle.push({})
 +    }
 +  }, [path])
 +
 +  return (
 +    <ins
 +      className="adsbygoogle"
 +      style={{ display: "block" }}
 +      data-ad-client="ca-pub-1234567890123456"
 +      data-ad-slot="9876543210"
 +      data-ad-format="autorelaxed"
 +    ></ins>
 +  )
 +}
 +export default AdsenseMatched
 +</code>
 +
 +''return''には、''関連コンテンツ''のコードから''<ins></ins>''の部分だけを書いている。
 +
 +----
 +===広告用のコンポーネントを読み込む===
 +''Layout.jsx''などのコンポーネントから、''AdsenseMain''や''AdsenseMatched''のjsxを読み込めば、その位置に広告が表示される。
 +
 +<code javascript>
 +    {process.env.GATSBY_FLAG_ADSENSE === "on" && (
 +      <AdsenseMain path={location.pathname} />
 +    )}
 +</code>
 +
 +<code javascript>
 +    {process.env.GATSBY_FLAG_ADSENSE === "on" && (
 +      <AdsenseMatched path={location.pathname} />
 +    )}
 +</code>
 +
 +''process.env.GATSBY_FLAG_ADSENSE === "on" &&''により、
 +環境変数''GATSBY_FLAG_ADSENSE''が''on''のときだけ広告を表示する。
 +=====aタグのかわりにgatsbyのLinkタグを使う=====
 +''a''タグだと、ページ全体が読み込まれる。
 +
 +''gatsby''の''Link''タグだと、変更のあるコンポーネントだけが再描画される。
 +(ページの表示が速くなる)
 +
 +''gatsby''の''Link''タグは、内部リンクにしか使えない。
 +
 +<code javascript>
 +import { Link } from "gatsby"
 +中略
 +
 +<Link
 +  to="/xxx"
 +>
 +  xxx
 +</Link>
 +</code>
 +
 +=====aタグのかわりにmaterial-uiのLinkタグを使う=====
 +<code>
 +warning  Using target="_blank" without rel="noreferrer" is a security risk: see
 +https://html.spec.whatwg.org/multipage/links.html#link-type-noopener
 +react/jsx-no-target-blank
 +</code>
 +
 +''a''タグに''target="_blank"''を使うと、Eslintのせいで上記のような警告が出る。
 +
 +----
 +
 +<code javascript>
 +<a
 +    href="http://example.com"
 +    target="_blank"
 +    rel="noopener"
 +>
 +    example.com
 +</a>
 +</code>
 +''rel="noopener"''のところを、''rel="noopener noreferrer"''にすれば警告は出なくなる。
 +
 +----
 +
 +<code javascript>
 +import { Link as MuiLink } from "@material-ui/core"
 +
 +中略
 +
 +<MuiLink
 +    href="http://example.com"
 +    target="_blank"
 +    rel="noopener"
 +>
 +    example.com
 +</MuiLink>
 +</code>
 +
 +または、''material-ui''の''Link''を使えば''noreferrer''に関する警告は出なくなる。
 +
 +''Link as MuiLink''のように、''Link''に別名をつけているのは、
 +''import { Link } from "gatsby"''の''Link''と区別するため。
 +
 +=====gitの改行変換機能を無効化する方法=====
 +<code>
 +warning: LF will be replaced by CRLF in xxxxx.md.
 +The file will have its original line endings in your working directory
 +</code>
 +という警告が大量に表示されるときの対処方法。
 +
 +Gatsby.jsで''.md''を扱うと、環境によっては改行コードの自動変換が発生する。
 +このとき改行の数だけwarningが表示されてうっとうしい。
 +
 +----
 +
 +<code bash>
 +git config --global core.autoCRLF false
 +</code>
 +
 +gitコマンドで、改行変換機能をオフにする。
 +
 +===== Gatsbyのプロジェクトをデプロイする方法 =====
 +VSCodeのターミナルで
 +<code>
 +git add .
 +</code>
 +
 +VSCodeのSource Controlの画面から
 +コメントを入れてコミット
 +
 +VSCodeのターミナルで
 +<code>
 +npm run build
 +</code>
 +
 +ビルド完了後に
 +VSCodeのターミナルで
 +<code>
 +git push
 +</code>
 +
 +===== Gatsby.jsその他 =====
 +[[/javascript:gatsby:others|Gatsby.jsその他]]
  • 最終更新: 2022/04/05 17:24