Bundlers
Bundlers take your source files—JavaScript modules, CSS, images—and combine them into optimized output ready for the browser. Learn Webpack, Vite, Rollup, and key concepts like tree shaking and code splitting.
What does a JavaScript bundler do?
A bundler (Vite, webpack, esbuild, Rollup) takes your many source files and npm packages and produces a few optimised files the browser can load quickly. Along the way it resolves imports, transpiles TypeScript and JSX, minifies, removes unused code (tree-shaking) and splits code into chunks. Vite is the most popular choice for new projects.
npm create vite@latest my-app
cd my-app && npm install
npm run dev # dev server with instant hot reload
npm run build # optimised files in dist/Bundler Comparison
| Bundler | Dev Speed | Build Speed | Tree Shaking | Best For |
|---|---|---|---|---|
| Webpack | Medium | Medium | ✅ Good | Large enterprise apps |
| Vite | ⚡ Instant (ESM) | Fast (Rollup) | ✅ Excellent | Modern SPAs, React/Vue |
| Rollup | Slow | Fast | ✅ Best | Libraries, npm packages |
| Parcel | Fast | Medium | ✅ Good | Zero-config prototypes |
| esbuild | ⚡ Fastest | ⚡ Fastest | ✅ Good | CLI tools, inside Vite |
Common Pitfalls
Interactive Demo
Code Editor
<p>A bundler turns many source files into a few optimised ones:</p>
<pre>src/
main.js import { formatPrice } from "./utils.js"
utils.js export function formatPrice… export function unused…
styles.css
↓ npm run build (Vite)
dist/
index.html
assets/index-3f9a2c.js ← minified, unused code removed (tree-shaking)
assets/index-81bd0e.css ← hashed names: safe to cache forever</pre>
<pre>// vite.config.js
import {
defineConfig,
} from "vite";
export default defineConfig({ build: { sourcemap: true } });</pre>Preview
Bundlers — step by step
Why Bundlers Exist
Browsers historically couldn't natively import hundreds of separate module files efficiently. Bundlers crawl the import graph starting from an entry point, combine all modules into one or more output files, and apply transformations like minification and transpilation.
🎯 Quick Check
What is tree shaking in the context of JavaScript bundlers?
JavaScript Bundlers: summary
Key points
- In development, Vite serves native ES modules, so start-up is instant; for production it bundles with Rollup.
- Tree-shaking only works with ES module
import/exportsyntax. - Dynamic
import()tells the bundler to create a separate chunk that loads on demand. - Frameworks like Next.js configure the bundler for you.
Frequently asked questions
›Do I need a bundler?
Not for small sites: browsers support ES modules natively. You'll want one when you use npm packages, TypeScript, JSX or a framework, or when you care about load performance.