Mastodon hachyterm.io

How to inline critical CSS transformed via Hugo Pipes

I use Hugo pipes to process my CSS files written in Sass.

Example:

{{- $critical := resources.Get "scss/critical.scss" | resources.ToCSS }}
{{- if hugo.IsProduction }}
{{- $critical = resources.Get "scss/critical.scss" | resources.ToCSS | resources.Minify }}
{{- end }}
<head>
  <link rel="stylesheet" href="{{ $critical.RelPermalink }}" />
// more code

Easy, peasy. I can use the optimized CSS as an external link to my stylesheet.

But how can I inline CSS?

The Hugo documentation is extensive, but sometimes it’s hard to find what you need.

The solution is easy after all, but it still took me two days to find.

You need to take the Hugo resource’s content and pipe it to the safeCSS function:

1
2
3
4
5
6
7
{{- $critical := resources.Get "scss/critical.scss" | resources.ToCSS }}
{{- if hugo.IsProduction }}
{{- $critical = resources.Get "scss/critical.scss" | resources.ToCSS | resources.Minify }}
{{- end }}
<head>
  <style>{{ $critical.Content | safeCSS }}</style>
// more code

Resources