lazyd3v blog
Several days ago I noticed that one of our react applications significantly increased in size. This application is bundled using webpack, so I added webpack-bundle-analyzer plugin to figure out what library bloats the bundle. When I looked at graph, I was quite surprised, because according to this our private components library used a lot of kilobytes. The problem was that this library was fully included, whilst app used only few components from it.
It seemed strange for me since we configured rollup to bundle library into ES modules and followed webpack’s tree shaking guide to exclude components that app is not using. But unfortunately it wasn’t enough.
After some research and experiments, I added this magical line to rollup’s config:
preserveModules: true
By default, rollup tries to create as few chunks as possible, so it bundles all modules in one file except modules imported with dynamic import syntax. If this option is enabled, rollup keeps original file structure.
I don’t know exact reason why, I don’t exclude I could make some mistake in webpack config (but I checked everything several times, trust me). Anyway, in my case webpack performed much better tree-shaking if library was bundled into multiple files. As a result application’s size was reduced by 150kb (not gziped), quite nice 🙂