1 Webpack rule that may reduce your CSS file size dramatically

webpack tree shaking illustration

As you’re writing your application, your CSS code will grow bigger in file size.

And if you have other engineers working on it, that CSS code will grow 2-3 times faster.

You then become terrified of removing a style in your stylesheet because you don’t know what it will affect.

As engineers we should remove dead code, and prevent as much of it to be deployed to production.

But this task takes a lot of time, and time is something we don’t always have.

But we can take action on this problem by using a technique called tree shaking that Webpack provides us with.

What’s is tree shaking

Tree shaking is a technique to remove any code that will not be executed.

Think of your application as a tree. Your code, and libraries are the leafs.

But some of that code doesn’t get used and it causes your leafs to turn brown, and weak.

The best way to remove that dead code is to shake it off the tree, so the tree remains with only green leaves.

This technique helps to reduce file size and improve performance.

Requirements to perform Webpack’s tree shaking feature

To be able to use Webpack’s tree shaking feature, you’ll need to have Webpack version 4.

And it also relies on ES2015 import, and export module syntax.

This means you need to use the CSS loader library to be able to import or require() CSS into your JavaScript application.

Tree shaking with Webpack in webpack.config.js file

As you’re writing your Webpack rule for CSS, you must add a property called sideEffects and give it a value of true.

Cue css for tree shaking technique

Now that you cued up your file to be shaken up! You’ll need to make sure Webpack is in production mode for it to fire up.

webpack production mode to execute side effects

That’s it!

Tree shaking with package.json file

You may also cue up your files for tree shaking in the package.json file.

Tree shake through package.json file

You may pass an array of files, or just give it a value of true or false.


By default Webpack side effects property is set to false; which doesn’t enable the tree shaking technique.

By flipping the switch and turning the value into true, it will enable the tree shaking technique, and reduce your CSS file size by removing unused code.

Smaller CSS files means better performance.

Let me know what other methods you use to reduce your CSS file size.

I like to tweet about code and post helpful code snippets. Follow me there if you would like some too!