Tree Shaking and Code Splitting: How to Build Faster Web Apps
As JavaScript projects grow, bundle sizes tend to explode. That means slower load times, higher bandwidth usage, and frustrated users.
Two techniques have helped me drastically improve performance in production apps: Tree Shaking and Code Splitting.
Let’s break them down what they are, how they work, and how to use them with real examples.
🌲 What is Tree Shaking?
Tree Shaking is the process of removing unused or “dead” code during the build step.
If a function, variable, or module isn’t actually used anywhere, it gets excluded from the final bundle.
It’s called “tree shaking” because the build tool shakes the dependency tree and drops dead leaves 🍃.
✅ Example
// utils.js
export function usedFunction() {
console.log("I'm used!");
}
export function unusedFunction() {
console.log("I'm not used!");
}
// main.js
import { usedFunction } from "./utils.js";
usedFunction();
When bundled with a tool like Webpack, Rollup, or Vite in production mode, the unusedFunction will be automatically removed from the output bundle.
⚙️ How to Enable Tree Shaking in Webpack
Tree shaking works only with ES modules (ESM) that means you must use import and export, not require.
Here’s a minimal Webpack configuration that supports it:
// webpack.config.js
module.exports = {
mode: "production", // Important: enables minification and tree shaking
entry: "./src/main.js",
output: {
filename: "bundle.js",
path: __dirname + "/dist",
},
optimization: {
usedExports: true, // Marks used exports for tree shaking
},
};
That’s it! Once you build your project with webpack --mode production, unused code is automatically removed.
✂️ What is Code Splitting?
Even with tree shaking, your JavaScript bundle can still be large.
Code Splitting solves that by splitting your code into smaller chunks that load on demand.
Instead of sending everything at once, the browser downloads only what’s needed at that moment.
✅ Example
Let’s say your app has two routes: Home and Dashboard. You don’t need to load the Dashboard code until the user actually visits it.
// home.js
export default function Home() {
console.log("Home Page");
}
// dashboard.js
export default function Dashboard() {
console.log("Dashboard Page");
}
// main.js
import("./home.js").then((module) => {
module.default();
});
// Later, when needed
document.getElementById("loadDashboard").addEventListener("click", () => {
import("./dashboard.js").then((module) => {
module.default();
});
});
Here, the import() call dynamically loads a module only when it’s needed.
Webpack (or Vite) automatically creates a separate chunk for each dynamically imported module.
⚙️ Code Splitting in React
React makes this super easy with React.lazy() and Suspense.
import React, { Suspense, lazy } from "react";
const Dashboard = lazy(() => import("./Dashboard"));
function App() {
return (
<div>
<h1>My App</h1>
<Suspense fallback={<p>Loading...</p>}>
<Dashboard />
</Suspense>
</div>
);
}
export default App;
Here, Dashboard will only load when it’s actually rendered perfect for improving the initial load performance of your app.
⚡ Combine Tree Shaking + Code Splitting
These two techniques work beautifully together.
Tree Shaking removes code you don’t use.
Code Splitting loads code only when you need it.
Together, they reduce your initial load size and total JavaScript payload, resulting in:
✅ Faster first paint
✅ Better Core Web Vitals
✅ Happier users
🧠 Final Tips
Use webpack-bundle-analyzer to visualize your bundle size.
Keep an eye on side effects if your module has side effects, Webpack won’t tree shake it unless you mark it as safe:
// package.json
{
"sideEffects": false
}
Always build in production mode (--mode production) tree shaking only happens then.
Avoid using CommonJS (require, module.exports) if you want tree shaking to work effectively.
🔍 Conclusion
Tree Shaking and Code Splitting are essential for any modern web app.
They don’t just make your bundles smaller they make your apps feel faster.
If you’re serious about web performance, start using these two today. Your users (and Lighthouse scores) will thank you.
💬 Have you implemented tree shaking or code splitting in your projects?
What tools or techniques have worked best for you?
Drop your thoughts in the comments below I’d love to hear how you optimize your bundles!
Top comments (0)