Removing unnecessary CSS using PurgeCSS
- 2023年7月03日
- 技術情報
Sending more CSS than you need not only results in latency and a bad experience, it also negatively impacts the Core Web Vitals that Google uses to measure your site’s SEO performance. Unused CSS occurs when the style file sent to the client contains rules that are not used by any page on the site. Some problems can occur.
- Bundle size: Including unused CSS in the front-end application bundle shipped to the client unnecessarily increases its size. This results in longer load times, higher bandwidth consumption, and impacts initial rendering and page navigation.
- Code Confusion : When your code base contains a lot of superfluous CSS rules, it becomes even more difficult to identify and maintain the styles that are actually being used. This confuses developers and can lead to errors and inconsistencies.
- Web Vitals: Google Lighthouse, a tool that measures a site’s Core Web Vitals, flags unused CSS as a problem. A low score on these metrics means that Google is evaluating the user experience provided by your site negatively, leading to lower SEO rankings.
About PurgeCSS
PurgeCSS is a tool to remove unused CSS. It can be part of your development workflow.
When you are building a website, you might decide to use a CSS framework like TailwindCSS, Bootstrap, MaterializeCSS, Foundation, etc… But you will only use a small set of the framework, and a lot of unused CSS styles will be included. This is where PurgeCSS comes into play. PurgeCSS analyzes your content and your CSS files. Then it matches the selectors used in your files with the one in your content files. It removes unused selectors from your CSS, resulting in smaller CSS files
Here is a short demo of what it’s looks like.
npm i -D @fullhuman/postcss-purgecss
and add the PurgeCSS plugin to the PostCSS configuration:
const purgecss = require('@fullhuman/postcss-purgecss')
module.exports = {
plugins: [
purgecss({
content: ['./**/*.html']
})
]
}
PurgeCSS will remove the CSS that is not in the files specified in the content
option.
You can learn more about PurgeCSS here.
Yuuma
yuuma at 2023年07月03日 10:00:00