Lesson 74 - JavaScript Module Bundlers : Introduction to Webpack, Parcel, etc.
Modular JavaScript is awesome, but when you split your app into many files and start using import/export syntax, the browser can't always run them as-is, especially in older environments. That’s where Module Bundlers come in.
What is a Module Bundler?
A module bundler takes multiple JavaScript files and combines (or “bundles”) them into one or more files that can run in the browser efficiently.
Think of it as a smart tool that:
- Resolves dependencies between modules.
- Transpiles code (e.g., using Babel for older browser support).
- Optimizes code for performance (minification, tree-shaking).
- Handles non-JS assets like CSS, images, etc. (via plugins/loaders).
Popular JavaScript Module Bundlers
Bundle | Description |
---|---|
Webpack | The most powerful and configurable bundler. Very flexible but has a learning curve. |
Parcel | Zero-config bundler. Automatically detects how to bundle your app. Great for beginners. |
Vite | Fast build tool powered by native ES modules. Extremely fast during development. |
Rollup | Great for libraries. Supports tree-shaking out of the box and produces smaller bundles. |
Why Use a Module Bundler?
- To use modern JavaScript features (ES6+) and still support older browsers.
- To structure your app with multiple files and dependencies.
- To improve load time with optimization.
- To include CSS, images, and other resources in the JS workflow.
How Bundlers Work (Basic Flow)
Your JS files (with imports/exports)
|
Module Bundler
|
Final bundled JS file (e.g. bundle.js)
Example: Parcel Setup in 2 Minutes
-
Install Parcel
npm install -g parcel-bundler
-
Create project structure
project/ |-- index.html |-- index.js |-- utils.js
-
Use ES6 supports
// index.js import { greet } from './utils.js'; greet("LanceCourse");
// utils.js
export function greet(name) {
console.log(`Hello, ${name}!`);
}
- Bundle and run:
parcel index.html
Parcel will auto-bundle and serve it at
http://localhost:1234
.
Try Your Hand
Install Parcel, create two files (math.js
and main.js
). Export a multiply()
function from math.js
, import and use it in main.js
, and view the result in the browser using parcel index.html
.