hugoでscssのビルド生成時にローカルサーバー・公開時で切り分け(autoprefixer追加)

hugoの初期設定のままではscssファイルからcss生成時にベンダープレフィックスがつかないので postcss.config.jsでautoprefixerを指定する

※参考 https://regisphilibert.com/blog/2018/07/hugo-pipes-and-asset-processing-pipeline/

npm install -g postcss-cli autoprefixer

ローカルにインストール時

npm install postcss-cli autoprefixer --save

hugoのテーマファイル からhead部分にあたら箇所をコピーし、 下記コードを追加する

{{- if eq (getenv "HUGO_ENV") "production" }}
  {{- with resources.Get "scss/style.scss" | toCSS | minify | fingerprint | resources.PostCSS (dict "config" "postcss.config.js")}}
<style>{{- .Content | safeCSS }}</style>
  {{- end }}
{{- else }}
  {{- $scss := resources.Get "scss/style.scss" | resources.PostCSS (dict "config" "postcss.config.js") }}
  {{- $style := $scss | resources.ToCSS }}
<link rel="stylesheet" href="{{ $style.Permalink }}">
{{- end }}  

scssファイルはassets配下におく。
postcss.config.js内でautoprefixerを指定

module.exports = {
    plugins: {
        autoprefixer: {
            overrideBrowserslist: [
                "last 2 versions"
            ]
        }
    },
}

テストサイトの生成時は下記コマンド

$ hugo

本サイト公開時は下記コマンド cssはインラインスタイル、googleAnalyticsコードの埋め込み処理を追加している

$ HUGO_ENV=production hugo --minify

css生成時にminifyしたかったが、ビルドに失敗するので、 hugoコマンド内にやむなく含めた。