Babel 7 and Tree Shaking

Understanding Tree shaking using Babel 7 as an example

Photo by Susanne Feldt on Unsplash

In this write up, we are going to look at a simple and practical way of understanding Tree shaking.

Compare Babel 6 and Babel 7

In order to appreciate the power that Babel 7 provides, we will look at how Babel6 and Babel 7 converts a piece of code that relies onObject.assign.

The image above demonstrate the output of running Babel 6 on a piece of code (inside index.js) using the provided configuration info in the .babelrc file.

The image below demonstrate the output of running Babel 7 on a piece of code (inside index.js) using the provided configuration info in the .babelrc file.

Showcasing output of Babel 7

Notice that unlike Babel 6 that includes unnecessary core-js modules, Babel 7 only adds the one module needed to execute our code on specified browsers (IE specifically).

At this point, you should why you should consider upgrade if you are still using Babel 6.

Tree shaking

Now, let’s talk about the process that Babel 7 takes when applying.

From .babelrc , Babel 7 notices that you want your code to run on IE and Safari. After that it looks at your code and finds Object.assign , which is not supported by IE. So, Babel 7 finds Object.assign polyfill and includes it in the output file.

Now we can craft our definition of Tree shaking which is basically,

An optimization process that a build tool takes to include only the code that can ever be executed.

Wrapping up

The main take away is that Babel 7 uses Tree shaking optimization process by writing its own code including only pieces that are needed to run your code on ie 9 and Safari 12.

I hope this helps those Framework and library maintainers who are still using babel 6 or who are unsure how Tree shaking technic can help them ship less code! And please feel free to comment with questions and disagreements.