Enable tree shaking on 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 thing 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.
My component library has it’s own package.json with sideEffects set to false.
Setting sideEffects to false is essentially us giving permission to Webpack to perform code splitting on our modules.
The application that imports my button uses Webpack for bundling.
Webpack will take care of removing the unused code when I bundle my application.
If I choose not to import my button component into my main application, compile my application and search the bundle.js file, I won’t see any reference to the button component.