π¦ What is a Bundler?
π Definitionβ
A Bundler is a tool that combines multiple files and modules into one or a few files. It optimizes various resources such as JavaScript, CSS, and images, and transforms them to be efficiently loaded in browsers. Representative examples include Webpack, Vite, Rollup, and Parcel.
π― Understanding Through Analogiesβ
Moving Company Analogyβ
Comparing a bundler to a moving company:
Before Moving (Before Bundling)
Household Items:
ββ Living Room: Sofa, TV, Table (JavaScript files)
ββ Bedroom: Bed, Desk, Wardrobe (CSS files)
ββ Kitchen: Refrigerator, Dishes (Image files)
ββ Bathroom: Sink, Towels (Font files)
Problems:
- Moving items one by one = Inefficient
- Unorganized = Hard to find
- Waste of space = Slow
Moving Company (Bundler):
1. Categorize items
2. Pack in boxes
3. Label
4. Efficient arrangement
5. Load on truck
After Moving (After Bundling):
π¦ Box 1: Furniture (main.js)
π¦ Box 2: Kitchen items (styles.css)
π¦ Box 3: Small items (assets)
Advantages:
- Transport all at once = Fast
- Organized = Easy to find
- Space efficient = Optimized
Library Analogyβ
Scattered Books (Before Bundling)
- 1000 books scattered on the floor
- Hard to find
- Waste of space
- Dust accumulation
Library System (Bundler)
1. Categorize by subject
2. Organize on shelves
3. Create index
4. Apply labels
Organized Library (After Bundling)
- Shelves by category
- Fast search
- Space efficiency
- Clean management
Cooking Preparation Analogyβ
Before Preparing Ingredients (Before Bundling)
Entire Refrigerator:
- 20 types of vegetables
- 5 types of meat
- 30 types of seasonings
- All in different locations
Chef (Bundler):
1. Check today's menu
2. Select only necessary ingredients
3. Prepare
4. Arrange in cooking order
Mise en Place (After Bundling)
- Only necessary ingredients organized
- Ready to cook immediately
- Efficient
- Time-saving
βοΈ How It Worksβ
1. Need for Module Systemβ
// Problem: Global pollution
// Loading multiple scripts in HTML
<!DOCTYPE html>
<html>
<head>
<script src="utils.js"></script>
<script src="math.js"></script>
<script src="app.js"></script>
</head>
</html>
// utils.js
var name = 'Utils';
function log(msg) {
console.log(msg);
}
// math.js
var name = 'Math'; // β Conflict! Overwrites name from utils.js
function add(a, b) {
return a + b;
}
// app.js
console.log(name); // 'Math' is printed (expected: 'Utils')
log('Hello'); // Works but unclear where the function comes from
// Problems:
// 1. Variable name conflicts
// 2. Dependency order matters
// 3. Global namespace pollution
// 4. Many HTTP requests for many files
// 5. Loads unused code