Remove unused css with React and Webpack

I am trying to remove unused css classes from my application using clean-css for WebPack.

To build this project, I use React , scss , WebPack and PostCss to build and compile everything.

So far I have managed to make progress, but something is wrong, and I do not know why, but the expected result is incorrect. I have a very simple setup for testing these scenarios, so these are my index.html and app.js files (the only files I have):

index.html

 <body> <nav> <a href="">home</a> </nav> <hr /> <div id="app"></div> <footer class="my-other-heading"></footer> </body> 

app.js

 class App extends React.Component { render() { return ( <h1 className="my-other-heading">Mamamia!</h1> ); } } render(<App />, window.document.getElementById("app")); 

In css files I use Normalize.css (with a bunch of css classes) and only 3 user classes:

 .my-class { background-color: #CCDDEE; } .my-heading { color: red; } .my-other-heading { color: blue; } 

The expected output should contain only these classes:

 html, body, nav, a, hr, div, footer, h1, .my-other-heading 

However, it has some other classes:

 .my-heading, h2, h3, h4, [type='checkbox'] (and other similar, eg: [type='button'] 

Why is this happening? It removes almost all the classes that it should, but some of them are still here, and classes that are not explicitly used in the index file. I don’t know if they are saved due to some other declaration on the side of React, but I only refer to src files. This is my css config config:

 new PurifyCSSPlugin({ paths: glob.sync([ path.join(__dirname, '..', 'src', '**/*.html'), path.join(__dirname, '..', 'src', '**/*.js'), ]), }) 
+7
reactjs webpack
source share
1 answer

You can try this webpack.config sample, it removes all unused classes from CSS and SASS files, however it adds classes from normalize.css

  module: { rules: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader', publicPath: '/dist' }) }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'sass-loader'], publicPath: '/dist' }) }, ... plugins: [ new HtmlWebpackPlugin({ title: 'Webpack2 - purify css', minify: { collapseWhitespace: true, }, hash: true, template: './src/index.html' }), new ExtractTextPlugin({ filename: '[name].css', disable: false, allChunks: true }), new PurifyCSSPlugin({ paths: glob.sync(path.join(__dirname, 'src/*.html')), purifyOptions: { info: true, minify: false } }), ... 
+1
source share

All Articles