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.
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.
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.
As you’re writing your Webpack rule for CSS, you must add a property called sideEffects and give it a value of true.
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.
You may also cue up your files for tree shaking in the 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.