Enable Tree Shaking to Optimize Your React Component Libraries with Webpack

An important part of building component libraries with React is making sure they are lightweight and optimized.
For example, I use Lodash a lot in my applications. I only use a handful of the functions Lodash has to offer. When I bundle my application for a production release, I don’t want the full 1.14 Mb library being pulled in.
Tree shaking, or “dead code removal”, is a technique that allows you to remove any unused code from a library.
In order to make tree shaking work, a few things need to be in place.
- The target library needs to be written in ES5 syntax or higher.
- The target library needs its package.json to have sideEffects set to false.
- You need to be using a JavaScript bundler that supports it, in my case, Webpack.
For the rest of the article, I’ll be going through an example of how I implemented tree shaking on a component library I built for a Monorepo.
My Monorepo has a package called components. All of my custom components are held here.
I have an oversimplified button component written in ES6 syntax.






