Tree shaking in Javascript - short explanation
Arika O
Posted on March 31, 2024
Tree shaking
is a term commonly used with Javascript and it refers to the process of eliminating dead code when trying to optimize it.
Before moving further, we should first understand what "dead code" means:
Dead code refers to code that is not being executed and has no impact on the final output. If you have
unused variables and functions
orlines that will never be reached
, you most likely suffer of an obvious case of "dead code".
Now that we understand what dead code is, you might ask yourself, when and why do we need to eliminate it?
THE WHY
When sending Javascript over the network, the code is often compressed. What this mean is that, in reality the code is much bigger after the browser decompresses it. Then the hard work starts: after is being downloaded by the browser, JavaScript must be parsed, compiled and then finally executed. Compared to other resources (images for example), Javascript is expensive to process, so we had to come up with ways of making the code more performant.
THE WHEN
Among other techniques, tree shaking is one way we can improve Javascript's performance by reducing bundle size.
Bundle size refers to the combined file size of all JavaScript code, libraries, and dependencies that are bundled together and served to the end-user in their browser.
Bigger bundle size means longer loading times, so the goal is smaller bundle sizes. Tree shaking can help us achieve that while the code gets compiled.
THE HOW
- We declare all of our
imports
andexports
for each of our Javascript modules. - The bundler (Webpack, Rollup, Parcel etc) analyzes our dependency tree during the compilation.
- All unused code is dropped from the final bundle.
IMPORTANT - take advantage of the ES6 imports and exports
If you want tree shaking to happen, you must use exports
and imports
in your modules. If you use require
, the bundler isn't able to reliably tell what is actually exported or imported so it can't determine what code is safe to drop.
RESOURCES
IMAGE SOURCE
Posted on March 31, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 22, 2024