You searched how to tree shake with Parcel and didn’t find it. It’s quick and easy. Every ones in a while we start some project and we start importing libraries. Project start to grow more and more and then we take a look how big our bundle is, and it’s huge. We don’t want to bundle code we don’t use, right? Let’s see how we can bring it down.
As of parcel v1.9.0 use cli option --experimental-scope-hoisting
parcel build index.html -d build --experimental-scope-hoisting
Although, you don’t need lodash in a first place, lodash has all those handy util functions we all love. You may only need debounce or groupBy or intersection or <add your function here> and you don’t want everything.
So, this is a simple code, just to show you how it works:
For visualization purpose I’m using parcel plugin.
Now if we refactor code like this:
It goes down: 92.2KB → 15.41KB, 83.28% smaller size for free 😎⚡️🎉
But we want to write functional style code and do some transformations on arrays or objects. Do we really need to import everything?
With a little bit of magic and custom chain function, we can tree shake it.
I wouldn’t recommend this, because it’s a hack, but it works 😀
92.2KB → 17.86KB, 80.06% smaller size, but still it’s a hack.
Lodash chaining future is near
What if I told you that we don’t need lodash hacking and we don’t need lodash/fp. We don’t need lodash flow or similar pipe techniques.
What if we can use native js to make chainable transformations.
There is pipe operator proposal and when parcel enable babel 7 this will became reality, until then we can use babel 6 pipe operator workaround.
Look how pretty code looks, 92.2KB → 16.87KB it’s awesome.
Bonus (rxjs v6)
I must mention rxjs, no need for whole new post just for rx.
I have love-hate relationship with rxjs, because it is a library with great features. But I just don’t want to add 200KB of minified code to my app or to add it like an external dependency.
So let’s tree shake it, because we can 😎
214.84KB → 11.45KB, 94.67% smaller size for free ️🎉
Parcel js bundler is still in development so it’s not yet battle tested. It still miss some features, but it’s a great tool. With tree shaking feature, it’s awesome tool, try it. Tree shake with --experimental-scope-hoisting.
Keep calm and tree shake those apps!