PurgeCSS

Donate

Become a backer or sponsor to support our work.

Sponsors

Sometimes you may be surprised that some styles are missing from the production environment, most likely because they have been removed by PurgeCSS. This article describes how to prevent styles from being deleted by PurgeCSS.

There are multiple ways to add styles to PurgeCSS’s safelisting, so that the styles won’t be get removed by PurgeCSS.

Safelist with Comments

This approach uses special comment to tell PurgeCSS do not to remove the styles.

1/*! purgecss start ignore */
2
3// STYLES GOES HERE.
4
5/*! purgecss end ignore */

Safelist with Configuration

HB allows configuring PurgeCSS, this approach is useful to add some classes, ids and tags which used by JavaScript, since Hugo unable to detect used styles in JS way.

assets/hb/modules/[name]/purgecss.config.toml
1classes = []
2ids = []
3tags = []
4attributes = []
5safelist_deep = []
6safelist_greedy = []
7safelist_standard = []
NameTypeDescription
classesarrayHTML class name, such as w-100, bg-success.
idsarrayHTML id.
tagsarrayHTML tags, such as h1, a.
attributesarrayHTML attributes, e.g. data-bs-theme.
safelist_deeparrayPurgeCSS safelisting patterns1.
safelist_greedyarrayPurgeCSS safelisting patterns1.
safelist_standardarrayPurgeCSS safelisting patterns1.

Testing

We’re able to test it locally with -e, --renderToDisk and --disableFastRender flags.

1hugo server \
2  -e production \
3  --gc \
4  --renderToDisk \
5  --disableFastRender \
6  -b http://localhost:1314 \
7  -p 1314

Further Reading

razonyang
Thursday, November 21, 2024 Saturday, April 15, 2023