Configure PostCSS to not remove all the things

Hugo has built-in support for CSS purging with PostCSS. To tell PostCSS which HTML elements are in use, include the below configuration in config.yaml:

build:
  writeStats: true

This configuration generates a hugo_stats.json file, which PostCSS can use as a reference. In postcss.config.js, include:

const purgecss = require('@fullhuman/postcss-purgecss')({
  content: [ './hugo_stats.json' ],
  ...
});

module.exports = {
   plugins: [
      ...(process.env.HUGO_ENVIRONMENT === 'production' ? [ purgecss ] : [])
    ]
 };

The parser that generates hugo_stats.json is naive and built for speed. If this results in PostCSS overpurging elements, it is possible to add custom ignore rules directly into the CSS.

ignoring the next rule

/* purgecss ignore */
h1 {
  color: blue;
}

ignoring the current rule

h1 {
  /* purgecss ignore current */
  color: blue;
}

Ignoring a range of rules

/* purgecss start ignore */
h1 {
  color: blue;
}

h3 {
  color: green;
}

/* purgecss end ignore */

Make sure there are no newlines between /* purgecss start ignore */ and the rule immediately following the comment (unless you like watching things fail).

There are probably better ways of accomplishing the above, but it works so 🤔

…postcss-import strict­ly adheres to the CSS spec and dis­al­lows @import state­ments any­where except at the very top of a file, so we can’t mix them in togeth­er with our oth­er CSS or @tailwind directives.

source: Speeding Up Tailwind CSS Builds

Additional reading

Related