Hugo version 0.43 bundled a very VERY POWERFUL feature: the assets processing function. This function allows you bundle any css or js into a single bundle css or js file, alongside with fingerprint integrity checking, all directly from Hugo itself!
That is a +2 for Hugo.
As of current status, you can only use assets processing function against assets directory.
The default is ./assets
. For your local site, you can configure it using the assetDir
keyword.
For theme modules however, you do not have a choice but to use the default ./assets
directory.
After testing the function out in my Bissetii theme module, I agree with the development team that those assets should stay inside the assets directory. They are not static files but are as internal resources files to build for one. Hence, I would not recommend you to alter assetDir
location unless otherwise absolute necessary.
There are 3 stages for compressing an assets:
This is quite straightforward, all you need to do is form an assets list using slice function. Example:
{{- $assets := slice -}}
{{- $assets = $assets | append ( resources.Get "css/main.css" ) -}}
{{- $assets = $assets | append ( resources.Get "css/navbars/sidebar_from_left_with_opacity.css" ) -}}
{{- $assets = $assets | append ( resources.Get "css/footers/simple.css" ) -}}
{{- $assets = $assets | append ( resources.Get "css/typography.css" ) -}}
Remember to place all the files inside ./assets/css
accordingly. Also, keep in mind that resources.Get
know the differences between css and js. Hence, you can't simply mix them up.
Next is to compress the resources. It's a one-liner:
{{- $css := $assets | resources.Concat "myBundledCSSName.css" | resources.Minify | resources.Fingerprint "sha512" -}}
This generates the final output and save under $css
(for javascript, you can use $js
). If you notice, the list gathered previously are passed into 3 stages processing:
resources.Concat
- bundle all the assets together into 1 file and name it according to the given name.resources.Minify
- minify the bundled asset file by stripping off necessary whitespace.resources.Fingerprint
- add a file integrity check with the minified bundled asset file.Now that you have the asset, you can use it. Depending on your asset type, a typical linking would be:
<link rel="stylesheet"
href="{{- $css.Permalink -}}"
integrity="{{- $css.Data.Integrity -}}" />
{{- if eq $mode "async" -}}
<script async type="text/javascript"
src="{{ $js.Permalink }}"
integrity="{{ $js.Data.Integrity }}"></script>
{{- else -}}
<script defer type="text/javascript"
src="{{ $js.Permalink }}"
integrity="{{ $js.Data.Integrity }}"></script>
{{- end -}}
To inline into HTML, you simply do:
<style type="text/css">
{{ $css.Content | safeCSS }}
</style>
<script type="text/javascript">
{{ $js.Content | safeJS }}
</script>
Refresh your page and you should see all the linking is ready.
That's all about assets processing function in Hugo. Good job dev team!