What is Tree Shaking in JavaScript: Explained Simply
import and export statements to keep only the parts of code that are actually used, making your app smaller and faster.How It Works
Imagine you have a big tree full of branches, but you only want to keep the branches that have fruit. Tree shaking is like shaking the tree so that all the empty branches fall off, leaving only the useful fruit-bearing ones. In JavaScript, this means removing code that your app never uses.
Bundlers like Webpack or Rollup look at your code's import and export statements to figure out which parts are actually needed. If a function or variable is never used, it gets dropped from the final bundle. This helps reduce the size of your JavaScript files, which makes your website or app load faster.
Example
This example shows how tree shaking removes unused code from a module.
export function usedFunction() { return 'I am used'; } export function unusedFunction() { return 'I am not used'; } // In another file: import { usedFunction } from './module.js'; console.log(usedFunction());
When to Use
Use tree shaking when you want to make your JavaScript bundles smaller and faster by removing code that is never called. It is especially helpful in large projects or when using big libraries where you only need a few features.
Modern build tools like Webpack, Rollup, and Vite support tree shaking automatically if you use ES6 modules with import and export. This makes your app load quicker and improves user experience.
Key Points
- Tree shaking removes unused code to reduce bundle size.
- It works best with ES6 module syntax (
import/export). - Supported by modern bundlers like Webpack, Rollup, and Vite.
- Helps improve app performance by loading less code.