When building modern JavaScript applications, performance is king. One key technique to optimize your code is tree-shaking — a smart process that shakes out the unused code, leaving behind only what your app actually needs.
What is Tree-Shaking and How Does It Work?
Tree-shaking is like pruning a tree by removing dead branches — it eliminates unused or dead code from your final JavaScript bundles. It's possible because modern JavaScript uses ES6 modules with their static import and export statements. This static structure allows bundlers like Webpack, Rollup, and Vite to analyze your code and discard anything not referenced.
Writing Library Code for Optimal Tree-Shaking
To build tree-shakeable libraries, avoid side effects and export your functions and components individually, rather than exporting a huge object. Use ES modules because CommonJS modules aren't statically analyzable and thus don't support tree-shaking well.
Good approach:
Common Mistakes That Break Tree-Shaking
- Using CommonJS (require / module.exports) instead of ES Modules (import / export).
- Exporting everything as one big object, rather than separate named exports.
- Including files or code with side effects, e.g., code that manipulates globals or runs immediately when imported.
- Mixing module types in the same bundle.
How Bundlers Use ESM for Dead Code Elimination
- Webpack: Uses the mode: 'production' config and sideEffects flags in package.json to safely prune code.
- Rollup: Designed with tree-shaking at its core and excels in shaking unused modules.
- Vite: Leverages ES modules and Rollup under the hood for fast builds and optimization.