Sep 24, 2025

JavaScript Tree-Shaking Explained: Optimize Your Code & Eliminate Dead Code

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

Bundlers scan your entry points and trace all import and export statements in ES modules, building a dependency graph. Anything never imported or referenced is considered dead code and eliminated from the final bundle — making your output smaller and faster.
  • 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.

Developer Tips

Proper use of ES modules, careful export patterns, and avoiding side effects are your keys to maximizing tree-shaking. Smaller bundles mean faster load times and better user experiences.
Need help migrating to ES modules or configuring bundlers for tree-shaking? Just ask!


EmoticonEmoticon