2

Configure PurgeCss to not remove certain styles

 3 years ago
source link: https://barryvanveen.nl/blog/68-configure-purgecss-to-not-remove-certain-styles
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Configure PurgeCss to not remove certain styles

4 days ago, no comments yet, Barry van Veen

If you have used PurgeCSS before, you know it is really good at removing unused css styles. This is great, but you immediately start running into another problem: it removes styles that you DO need.

This project I'm working on contains some dynamic styles. You write markdown in the backend and that gets converted into html. Throw in some syntax highlighting and suddenly you have all these styles that you do need but are not actually in any template.

My first hacky solution was creating a template file that just contained these "dynamic" elements so that PurgeCSS would pick them up and not remove it from the stylesheet. It is a very simple solution that worked so far, but I had to keep making sure all my essential styling was kept.

Today I properly read the PurgeCSS docs and discovered 2 easy solutions that I want to share with you.

PurgeCSS safelist

When I added some syntax highlighting to the project using highlight.js I also added a safelist configuration to the PurgeCSS Webpack plugin I use:

new PurgecssPlugin({
    paths: ...,
    defaultExtractor: ...,
    safelist: {
        deep: [/hljs-/],
    }
}),

This will basically keep all css selectors that contain hljs-, which is exactly what I need.

Read the docs on PurgeCSS safelist configurations for more options.

CSS comments

Another way to indicate that styles should be kept is by placing some specific css comments. In my case, I have only a single file with some customers styles.

That file now contains 2 comments:

/*! purgecss start ignore */
    // customer styles go here
/*! purgecss end ignore */

The docs also contains ways of safelisting a single rule.

These are two very nice solutions and more maintainable solutions. Hope it helps you in your project too!

Comments

No comments yet. Be the first to comment on this article.

Add your comment

Your name
Email address (not visible to others)
Your message

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK