Rename minified resource

I’ve got a bit of a unique problem: I require certain assets to have specific output names. To save bandwidth I would also like to minify the assets (mostly CSS files) however using resources.Minify on an asset adds a suffix to the name.

I have tried to rename the asset back to the original name using the resources.Copy function: {{ (resources.Get "style.css" | resources.Minify | resources.Copy "style.css").RelPermalink }} however this prevents the minification from working.

I then tried renaming the source asset then renaming it to the desired name after the minification. In this case the rename appears to take effect before the minification so I’m still left with the “.min” suffix: {{ (resources.Get "style_source.css" | resources.Minify | resources.Copy "style.css").RelPermalink }}

Any help would be greatly appreciated!

Try something like this

{{- $styles := resources.Get "style.css" | minify | resources.Copy "style1.css" -}}

Then use it like this

<link rel="stylesheet" href="{{ $styles.RelPermalink }}">

The resources.Copy method retains the min identifier in the resulting path.

Examples:

{{ (resources.Get "x.css" | minify).RelPermalink }} --> /x.min.css
{{ (resources.Get "x.css" | minify | resources.Copy "y.css").RelPermalink }} --> /y.min.css
{{ ((resources.Get "x.css" | minify).Content | resources.FromString "y.css").RelPermalink }} --> /y.css

The last one does what you want. In full:

{{ $css := (resources.Get "style.css" | minify).Content | resources.FromString "style.css" }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}">

Credit to @pamubay reference https://discourse.gohugo.io/t/36397/3.

2 Likes

Thanks, that works perfectly!

Is it possible to explain why copy works in this way?

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.