How to Remove Unused CSS Using Webpack 4

Remove unused CSS classes from frameworks like bootstrap in a react project

As djfdev already wrote purgecss works quite well: purgcss simply searches all JavaScript files for occurrences of the CSS class strings of the used CSS files and removes those which cannot be found.

Purge-css is removing all css stylings instead of just the unused ones

Since your app is a ReactJS App, you want to purge css classes not used in the Javascript bundle compiled for the dev or production environment.

You can update your postcss.config.js file to match on .js files.

module.exports = {
plugins: [
purgecss({
content: ["./src/**/*.js"],
// Treat every word in the bundle as a CSS selector
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []

}),
]
};

Remove unused css / js code on Release Build in Visual Studio

Use Webpack's Tree Shaking

Module bundler's like Webpack do it on the fly with the cost of minor configuration effort.



Related Topics



Leave a reply



Submit