Notes
Auto compiling Sass and SCSS in Hugo
This is a general overview of the ToCSS pipe in Hugo’s asset management
Hugo
2 minutes
1{{ $scss := resources.Get "scss/main.scss" }}
2{{ $css := $scss | resources.toCSS }}
3
4<link rel="stylesheet" href="{{ $css.RelPermalink }}">
- Your Sass files need to be in the
assets/folder for you to be able to pipe commands with|. By default the assetDir isassets/in the project root. By default, you can only have oneassetDir- You can mount your theme’s assets directory
themes/BLAH/assets/(i.e. multipleassetDirs) as a module with a custom mount configuration. Read: Hugo assets directory
- You can mount your theme’s assets directory
:=is also known as the walrus operator. It means definition and assignmentresources.Getlocates the filename given in Hugo’s assets filesystem and creates aResourceobject that can be used for further transformations.RelPermalinkwould get the relative permalink. Meaning/scss/main.cssinstead ofhttp://mysite.com/scss/main.css
1{{ $scss := resources.Get "scss/main.scss" }}
2{{ $css := $scss | ToCSS }}
3
4<link rel="stylesheet" href="{{ $css.RelPermalink }}">
1{{ $style := resources.Get "scss/main.scss" | resources.ToCSS }}
2
3<link rel="stylesheet" href="{{ $style.RelPermalink }}">
You can also specify options like you normally would if you ran dart-sass or sass CLI
1{{ $options := (dict "targetPath" "style.css" "outputStyle" "compressed" "enableSourceMap" (not hugo.IsProduction) "includePaths" (slice "node_modules/myscss") "transpiler" "libsass") }}
2{{ $style := resources.Get "sass/main.scss" | resources.ToCSS $options }}
- for
transpileryou can specifydartsassinstead of the defaultlibsass, but you’d need to have Dart Sass installed for that - setting
outputStyletocompressedwill handle Sass/SCSS files minification better than the more genericresources.Minify.
Troubleshooting
An error like below most likely means that the file is not in assetDir. Check your file paths and make sure the file path is included in your assetDir location(s)
execute of template failed at <resources.ToCSS>: error calling ToCSS: no Resource provided in transformation