Tree shaking is a optimization technique used to remove "dead code" from your JavaScript bundle. It ensures that only the code you actually use gets sent to the user's browser.
How it works:
• It relies on Static Analysis of ES6
import and export statements.• The bundler (like Webpack or Vite) tracks which functions or variables are being called.
• During the build process, it identifies exported code that has no references.
• These unused pieces are "shaken off" and excluded from the final production file.
Problem it solves:
It prevents bundle bloat. Without it, even if you use one line from a massive library, the whole library would be included, making your website slow to load.
Use case:
If you have a file
math.js with 20 different utility functions, but your app only imports add(), tree shaking will automatically delete the other 19 functions from your final build.