Minify and Load CSS Through Hugo

This post is about loading your CSS files with Hugo in an easy and efficient way, now that Hugo has asset and minification built-in. The advantages of using the functions that come with Hugo are that you don’t have to do any of the building yourself (or use a third party), it just does it!

There are a few steps involved in the code that we will walk through:

  1. Specify your main scss filename (the one where everything imports into).
  2. Specify your outputted filename.
  3. Define your options, if you are on a local server then we turn on source maps (for easier debugging), otherwise we minify the CSS for performance on our live environment.
  4. Build your CSS file using resources.Get.
  5. Load the CSS file into the HTML source.
1
2
3
4
5
{{- $cssSource := "scss/mymainscssfile.scss" }}
{{- $cssTarget := "css/style.css" }}
{{- $cssOptions := cond (.Site.IsServer) (dict "targetPath" $cssTarget "enableSourceMap" true) (dict "targetPath" $cssTarget "outputStyle" "compressed") }}
{{- $style := resources.Get $cssSource | toCSS $cssOptions }}
<link rel="stylesheet" href="{{ $style.RelPermalink }}">

Note: the hyphen in {{- means remove all whitespace before this.

This will output something like:

1
<link rel="stylesheet" href="/css/style.css">

Verify Authenticity (optional)

If you think there’s a possibility of your CSS being tempered with and you want to be extra careful then you can check it’s integrity by using the “fingerprint” option. To do this, change the last 2 lines to look like this:

1
2
{{- $style := resources.Get $cssSource | toCSS $cssOptions | fingerprint }}
<link rel="stylesheet" href="{{ $style.RelPermalink }}" integrity="{{ $style.Data.Integrity }}">

This will output something like:

1
<link rel="stylesheet" href="/css/style.9eb7a4aa85871fc4fcf7531fe7a57fad0b4a7e698cd5861eddfb5ba4584ab7e5.css" integrity="sha256-nrekqoWHH8T891Mf56V/rQtKfmmM1YYe3ftbpFhKt&#43;U=">

Do you have an extra options you add? Or do you prefer to load your CSS in differently? Let us know in the comments below.