#ASKTHEINDUSTRY 18: What is Tree Shaking and why does it matter?

Alessandro Menduni
West Wing Solutions
2 min readMar 3, 2017

Tree shaking is one of those technique that aim at reducing the JavaScript bundle size.

It involves statically analysing the code in order to find which parts of a given module or library are not being used, and cut them off the final bundle.

You often end up needing only 20–40% of the code you are shipping to the final user.

Why does it matter? Typically it’s a work that makes sense in those apps that rely on lots of external libraries, especially as they grow in complexity and size. It’s a good thing that we can count on this huge JavaScript ecosystem, however, pulling in library after library, you often end up needing only 20–40% of the code you are shipping to the final user.

A couple of examples that might resonate with you:

  • You want to use jQuery, but maybe you’re just interested in a couple of functions, like $ and $.get
  • You are pulling in lodash but you’re using just a couple of functions to debounce and throttle your event listeners

If that sounds anything like you, check tree shaking out.

If you are using ES2015 import statement, here is what a static analyzer can do:

  • Build a dependency tree
  • Figure out which exported features of a module you are actually importing
  • Do the same thing with the dependencies (of the dependencies, of the dependencies…)
  • Concatenate in a single file only the stuff you need, and in the right order

Needless to say, this can reduce the size of you bundle by just so much!

If you are looking for a way to experiment with this idea, do check rollup.js out!

I read each and every comment, and look forward to see what you think! Also, this piece is part of the #ASKTHEINDUSTRY project, which is a distributed interview to the web industry: you ask, I’ll answer, or find someone who can! Drop a comment if there is anything I can help you with!

--

--

Alessandro Menduni
West Wing Solutions

JavaScript Engineer, passionate about testing JavaScript and software architecture