Skip to main content

What is tree shaking?

Tree shaking is a build optimization technique where unused code is removed from the final bundle. It is supported by modern bundlers: Vite, Webpack, Rollup, esbuild.

Put simply:

Tree shaking = "shaking the import tree" to keep only what is actually used.

The name is a metaphor: as if you "shake a tree" and the unneeded leaves (functions/modules) fall off.


Why is tree shaking needed?

To reduce:

  • the size of the final JS bundle
  • the application's load time
  • JS parsing and execution time
  • TTI (Time To Interactive)

Tree shaking is one of the key optimizations in modern SPAs (Vue, React, Svelte).


How does tree shaking work?

Tree shaking is possible thanks to two things:


1. Using ES modules (ESM)

js
import { fn } from './utils.js'

ESM imports are static, so they can be analyzed at build time. The bundler understands:

  • which functions are imported
  • which are not
  • which code is "dead"

2. Dependency analysis (dead code elimination)

The bundler detects code that is not used:

js
export function usedFn() { ... } export function unusedFn() { ... }

If unusedFn() is not imported anywhere, it is completely removed from the build.


Example with Vue

In Vue 3:

js
import { ref, reactive, computed } from 'vue'

If you do not use reactive, the bundler:

  • will NOT include reactive in the bundle
  • will keep only ref and computed

This became possible in Vue 3 thanks to its fully modular-friendly structure.

Vue 2 could not do this.


Where is tree shaking especially useful?

1. In large UI libraries

For example:

js
import { ElButton, ElTable } from 'element-plus'

The bundler includes only the components that are actually used.


2. When importing utility functions

For example, Lodash as lodash-es:

js
import { debounce } from 'lodash-es'

The bundler includes only debounce, not all of Lodash.


3. In large Vue + Vite/Webpack projects

ESM plus module optimization shrinks the bundle several times over.


Important conditions for tree shaking (asked in interviews)

For tree shaking to work, you need to:

Use ESM (import/export), not CommonJS (require, module.exports)

Webpack, Rollup, and Vite cannot correctly tree-shake CommonJS.

Avoid dynamic imports built from variables

Bad:

js
const name = 'module' import(`./${name}.js`)

The bundler cannot analyze such imports.

Avoid side effects

If a module has side effects on import:

js
console.log('I run when imported!')

it cannot be removed.


Summary (great for interviews)

Tree shaking is the process of removing unused code at build time. It is based on static analysis of ES modules. It lets you reduce the bundle size and speed up application loading. Vue 3 fully supports tree shaking; Vue 2 does not.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.