Optimize generated CSS by removing unused selectors (#2008)

Hugo generates stats about the HTML elements, IDs and classes that can be found in the website,
and we post-process the rendered CSS with postcss-purgecss that uses those stats to remove unused selectors.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
This commit is contained in:
Kévin Commaille 2024-12-10 23:55:14 +01:00 committed by GitHub
parent 54d872e19b
commit 1accb9e93f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 1240 additions and 279 deletions

View file

@ -0,0 +1,38 @@
{{- /*
A modified version of the head-css.html partial of Docsy, that adds a call to
`resources.PostProcess`, allowing post-processing of the generated CSS to
remove unused selectors.
*/ -}}
{{ $scssMain := "scss/main.scss" -}}
{{ $css := resources.Get $scssMain
| toCSS (dict "enableSourceMap" (not hugo.IsProduction)) -}}
{{/* NOTE: we only apply `postCSS` in production or for RTL languages. This
makes it snappier to develop in Chrome, but it may look sub-optimal in other
browsers. */ -}}
{{ if eq .Site.Language.LanguageDirection "rtl" -}}
{{ $css = $css
| postCSS (dict "use" "autoprefixer rtlcss" "noMap" true)
| resources.Copy (replace $scssMain "." ".rtl.") -}}
{{ else if hugo.IsProduction -}}
{{ $css = $css | postCSS -}}
{{ end -}}
{{ if hugo.IsProduction -}}
{{ $css = $css | minify | fingerprint | resources.PostProcess -}}
<link rel="preload" href="{{ $css.RelPermalink }}" as="style" integrity="{{ $css.Data.Integrity }}" crossorigin="anonymous">
{{ end -}}
{{ with $css -}}
<link href="{{ .RelPermalink }}" rel="stylesheet"
{{- with .Data.Integrity }} integrity="{{ . }}" crossorigin="anonymous"{{ end -}}
>
{{ else -}}
{{ errorf "Resource not found or error building CSS: %s" $scssMain -}}
{{ end -}}
{{- /**/ -}}