Skip to content

Chapter 7: The KonMari Method: Removing Unused Code with Tree Shaking

Of course. Now that we've ensured our files are cached effectively, let's circle back to optimizing the files themselves. This time, we'll look at a bit of magic performed by modern build tools: Tree Shaking.


The Scenario 📝

  • System: A modern web application that uses import/export (ES Modules).
  • Problem: A developer imports a large utility library like lodash-es just to use a single function, debounce.

Example Code:

javascript
// main.js
import { debounce } from 'lodash-es';

function handleInput() {
  console.log('Debounced event!');
}

const myInput = document.querySelector('#search');
myInput.addEventListener('input', debounce(handleInput, 300));

The Bottleneck (Without Tree Shaking) 🧐

Without tree shaking, the build tool (bundler) would see the line import ... from 'lodash-es' and conclude, "Okay, this application needs the lodash-es library." It would then include the entire lodash-es library (hundreds of different functions) in your final JavaScript bundle.

The Consequence: Your bundle gets bloated with hundreds of kilobytes of code that is never actually called, slowing down your page load.


The Solution: Tree Shaking ✅

  • The Logic: Tree shaking is a form of dead code elimination. It works just like shaking a tree to make the dead leaves fall off.
  • How It Works:
    1. The bundler (like Vite, which Nuxt uses) starts at your application's entry point.
    2. It builds a dependency graph, looking at all your import and export statements.
    3. It analyzes this graph to determine exactly which functions and variables from your imported libraries are actually used in your code.
    4. During the final build process, it completely removes any code that isn't used.

How Nuxt Handles This ✨

Tree shaking is a built-in and automatic feature of Nuxt's production build process.

Your only job as a developer is to make sure you write modern code:

  • Always use import and export syntax (ES Modules).
  • Avoid older patterns like require() (CommonJS) where possible, as they are harder for the bundler to analyze statically.

Analyzing the Results

With tree shaking enabled, the bundler analyzes our example code and realizes, "Ah, from lodash-es, this developer is only using the debounce function."

As a result, the final bundle will only include the code for the debounce function and any internal functions it depends on, not the entire library. The bundle size might shrink from several hundred kilobytes to just a few.


Conclusion:

  • Tree Shaking is a critical, automated optimization in modern web development workflows.
  • It helps keep your bundles small by eliminating unused code from the libraries you import.
  • To take advantage of it, simply stick to using import/export syntax.