Build drafts when serving
Run the hugo server command with the -D flag to build drafts: hugo server -D
I usually have an npm run serve
script in package.json that runs chores like building search index, creating OpenGraph and twitter images, etc. before serving my hugo site locally.
{
"scripts":{
"serve": "npm run prebuild && hugo server -D"
}
}
Exclude if drafts are built
.Site.BuildDrafts
returns true
when hugo server -D
runs. Therefore it can be used to conditionally exclude the analytics scripts from the head
when serving locally.
{{ if not .Site.BuildDrafts }}
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
{{ end }}
When hugo
is run without the -D
flag, the analytics section will be included as expected.