HugoでTailwindCSSを利用しAMP Validなページを生成する

HugoでCSSフレームワーク「Tailwind CSS」を利用し、AMP Validなページを生成する方法についてのメモです。

ポイント

  • HugoでPostCSSの仕組みを利用して、TailwindでCSSを組み立てる
  • Tailwind CSS v1.4からpergeCSSを内包し、設定方法が変わった

Tailwind CSSは、utility-firstなCSSフレームワークです。 あらかじめ決められたutilityのセットが用意されており、ユーザはそのutilityを組み合わせて任意のデザインを組み上げます。

一方、AMPの制約には、CSSのインライン化とCSSサイズが決められています。Tailwind CSSが用意するCSSをすべて利用した場合には、2413.4kBとなりAMPの制約を満たすことができません。そのため、HugoでTailwind CSSを利用してAMP Validなページを生成するためには、未使用CSSを削除し、サイズ圧縮が必要です。

Tailwind CSS ver.1.3までは@fullhuman/postcss-purgecssを利用していましたが、ver1.4からはTailwind自体にpurgeCSSを含むようになり、設定方法が変わりました。

head.html

Hugoの<head>を組み立てるテンプレート内で、postCSSを利用します。

{{ if .Site.IsServer }}
  {{ $style := resources.Get "css/styles.css" | postCSS (dict "config" "./assets/css/dev/postcss.config.js") | fingerprint }}
  <link rel="stylesheet" href="{{ $style.Permalink }}" data> 
{{ else }}
  {{ $style := resources.Get "css/styles.css" | postCSS (dict "config" "./assets/css/postcss.config.js") | minify }}
  <style amp-custom>{{ $style.Content | safeCSS }}</style>
{{ end }}

.Site.IsServerによって、ローカル開発と本番ビルドで挙動を変えています。

  • ローカル開発(huge server):スタイルシートとして読み込み
  • 本番ビルド(HUGO_ENV="production" NODE_ENV="production" hugo -gc):AMPカスタムCSSとしてインラインCSS化

ポイントは次の記述です。css/styles.cssを読み取り、Hugo PipesのpostCSSに渡し、./assets/css/postcss.config.js"の設定に従い、CSSを処理します。

{{ $style := resources.Get "css/styles.css" | postCSS (dict "config" "./assets/css/postcss.config.js") | minify }}

postcss.config.js

const themeDir = __dirname + '/../../';

module.exports = {    
    plugins: [        
        require('postcss-import')({path: [themeDir]}), 
        require('tailwindcss')(themeDir + 'assets/css/tailwind.config.js'), 
        require('autoprefixer'),
    ]
}

tailwind.config.js

tailwind.config.jsはTailwindの設定ファイルです。 purgemode: 'all'で未使用CSSを削除します。

 const themeDir = __dirname + '/../../';
 
 module.exports = {
   purge: {
     mode: 'all',
     content: [
       themeDir + 'layouts/**/*.html',
       'layouts/**/*.html',
       'content/**/*.html',
     ],
   },
   theme: {},
   variants: {},
   plugins: []
 }

参考

Tailwind v1.3系の際の設定は次のとおりでした。

const themeDir = __dirname + '/../../';

module.exports = {    
    plugins: [        
        require('postcss-import')({path: [themeDir]}), 
        require('tailwindcss')(themeDir + 'assets/css/tailwind.config.js'),
        require('@fullhuman/postcss-purgecss')({
            // Specify the paths to all of the template files in your project 
            content: [
                themeDir + 'layouts/**/*.html',
                'layouts/**/*.html',
                'content/**/*.html',
            ],
            whitelist: ['blockquote'],
            whitelistPatternsChildren: [/post$/],
            // Include any special characters you're using in this regular expression
            defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [], 
            fontFace: true
        }),    
        require('autoprefixer')({
            grid: true
        }),
        require('postcss-reporter'),
    ]
}

まとめ

  • Hugo Pipes「postCSS」を利用することで、Tailswind CSSでAMP Validなページを生成可能
  • Tailwind CSS ver1.4からフレームワーク自体にpurgeCSSの機能を含んだため、設定変更に注意

Backlinks

静的サイトジェネレータHugo
Hugo入門 静的サイトジェネレータ「Hugo」でシンプルブログサイトを構築する 静的サイトジェネレータ「Hugo」インストール 静的サイトジェネレータ「Hugo」〜公開方法〜 サイト構築 Hugoのテーマでsubmoduleを使う方法 HugoでのシンタックスハイライトにPython Pygmentsが不要となった HugoのRelated Contentを利用して関連記事を表示する gulpで画像の最適化 Hugoソースコードリーディング〜Taxonomy〜 Render Hooks for Code Blocksを利用してコードブロックにファイル名を表示する Hugoでブログカードを作成する(resources.GetRemote利用) Templates 【Hugo】Partial Templateでは複数returnを記述する早期Returnを使えない 【Hugo】images.TextでOGP画像を生成する Shortcodes Hugo Shortcodesの作り方 HugoのShortcodesを利用してAmazon紹介リンクタグを作成 HugoでAMP対応のブログカードを作る AMP対応 AMP向けのミニマルCSSフレームワーク「1BX」をHugoに導入した AMPページの最適化〜ぼくのAMPサイトがこんなに遅い訳がない〜 AMP OptimizerによるAMPのさらなる最適化 AMP Service WorkerでPrefetch Linksを実現する Data Driven Content Hugoで人気記事を表示するためJSONを返すAPIサーバを作りData-driven Contentを試してみた Tailwind CSS HugoでTailwindCSSを利用しAMP Validなページを生成する ビルド npm-run-allでローカルAPI serverとHugo serverを同時に実行する GitHub Actionsのスケジューラ実行を利用して定期的にビルドする Circle CIでHugoのビルド・デプロイを実行する コンテンツ作成 Git pre-commitフックでFrontmatterの「更新日時」を自動更新する Hugoでブログ記事一覧ページ(ブログアーカイブページ)を作成する 移行 はてなダイアリーからはてなブログ経由で独自ドメインのブログに記事を移行しました JekyllからHugoへの移行ポイント Hugoで生成した静的サイトのホスト先をさくらVPSからNetlifyに変更する 書籍
2017-12-31