Naoto Ishizawa/Hugo GitHub-StyleでGoogle Analyticsを有効にする

Created Fri, 29 Jan 2021 00:09:05 +0900 Modified Sat, 17 Dec 2022 21:58:21 +0000

公式ドキュメントには googleAnalytics = "UA-123456-789" というconfigがあり, これを記述すれば有効になると思ったけど実際にはならなかった。
https://themes.gohugo.io/github-style/#configtoml-example

$ echo 'googleAnalytics = "UA-123456-789"' >> config.toml
$ hugo server

themes/github-style/layouts/partials/extended_head.html を見ると HUGO_ENV で条件分岐していることがわかった。

<!-- Google Analytics -->
{{ if eq (getenv "HUGO_ENV") "production"}}
{{ with .Site.GoogleAnalytics }}
<script async src="https://www.googletagmanager.com/gtag/js?id={{ . }}"></script>
<script>
  if (navigator.doNotTrack !== '1') {
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());

    gtag('config', '{{ . }}');
  }
</script>
{{ end }}
{{ end }}

HUGO_ENV=production を設定することで解決🙂

$ HUGO_ENV=production hugo server

ちなみにちゃんとドキュメントにも記載ありました😇

Here is an sample. Note line 22 have env HUGO_ENV=“production”, makes sure googleAnalysis is loaded during production, but is not loaded when we are testing it in localhost.

https://themes.gohugo.io/github-style/#deploysh-example