Hi,
To optimize my site I am currently inlining and minifying CSS using the following code:
{{ with resources.Get "/css/tachyons-optimized.css" | minify }}
<style amp-custom> {{ .Content | safeCSS }} </style>
{{ end }}
What I really want to do as well is to remove all the CSS tags that are unused in the current document.
Is there a simple way to do this?
Any advice is helpful.
I personally consider purgecss simple enough. As a plugin for postcss you can use it with Hugo Pipes.
1 Like
Can I bother your to share your configuration file?
Sure! Here’s how I did it on one of my sites :
postcss config:
module.exports = {
plugins: {
'@fullhuman/postcss-purgecss': {
content: ['themes/termux/layouts/**/*.html'],
whitelist: [
'highlight',
'language-bash',
'pre',
'code',
'content',
'h3',
'h4',
'ul',
'li'
]
},
autoprefixer: {},
cssnano: { preset: 'default' }
}
};
Hugo Pipes:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<meta name="description" content="{{ .Description }}">
<title>{{ .Site.Title }}</title>
{{ if eq (getenv "HUGO_ENV") "development" }}
{{ $cssOpts := (dict "enableSourceMap" true "includePaths" (slice "node_modules/bulma" "assets/scss")) }}
{{ $styles := resources.Get "scss/main.scss" | toCSS $cssOpts | postCSS }}
<link rel="stylesheet" href="{{ $styles.Permalink }}" media="screen">
{{ else }}
{{ $cssOpts := (dict "enableSourceMap" false "includePaths" (slice "node_modules/bulma" "assets/scss")) }}
{{ with $styles := resources.Get "scss/main.scss" | toCSS $cssOpts | postCSS | minify | fingerprint }}
<style>{{ .Content | safeCSS }}</style>
{{ end }}
{{ end }}
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
This file has been truncated. show original
And here’s another project by budparr that uses Hugo + purgcecss:
8 Likes
Worked beautifully! Thanks!
Great solution but how would you go about modifying it for amp pages?
Amp requires inline CSS in head tag of every page. Amp doesn’t support stylesheet link.
So custom CSS would be different for every single page. I feel this is where PurgeCSS can make huge performance improvement. Not to mention amp pages has 50Kb hard limit for custom CSS.