I’ve done a bunch of trial and error on this and haven’t figured it out. Hoping someone can point me in the right direction.
I’m trying to optimize my site. The pipeline I’m trying to create for my CSS is: Compile from scss to css → Autoprefix → Minify → Purge.
Having trouble with the Purge part. It either doesn’t do anything or it breaks the site. This is what’s in my <head>
:
{{ $sass := resources.Get "scss/styles.scss" }}
{{ $toCssOpt := (dict "includePaths" "node_modules" "targetPath" "/assets/css/styles.css") }}
{{ $postCssOpt := (dict "use" "autoprefixer") }}
{{ $style := $sass | toCSS $toCssOpt | postCSS $postCssOpt }}
{{ if hugo.IsProduction }}
{{ $style = $style | minify | fingerprint | resources.PostProcess }}
{{ end }}
<link href="{{ $style.RelPermalink }}" rel="stylesheet">
But this doesn’t change the size of my CSS file, it stays at 208kB whether | resources.PostProcess
is there or not.
If I swap that out for | postCSS
, my CSS does get reduced to 20kB, but it breaks the site, my styles aren’t applied correctly anymore. Some of them are still there though, so it’s not like the CSS is completely gone.
But this isn’t what the docs say to do, so I’m not surprised it doesn’t work. It’s just what I’ve tried that actually does do anything.
I’ve checked and Hugo is creating the hugo_stats.json file, so I think my config.toml is correct.
Here is my postcss.config.js file:
const purgecss = require("@fullhuman/postcss-purgecss")({
content: ["./hugo_stats.json"],
defaultExtractor: (content) => {
const els = JSON.parse(content).htmlElements;
return [...(els.tags || []), ...(els.classes || []), ...(els.ids || [])];
},
safelist: [],
});
const autoprefixer = require('autoprefixer')
module.exports = {
plugins: [
...(process.env.HUGO_ENVIRONMENT === "production" ? [purgecss] : []),
],
};
I am running the server with this command: npx hugo serve --environment production
I’m using Bootstrap to build the site, so there should be a fair bit of CSS that can be purged. Maybe there’s something I have to configure differently because of how Bootstrap is put together?
Here is the whole repo: GitHub - schaefsteven/rocky-hutchins at testing