⚡ Lesson 22 of 30
Modules & Bundlers
Organise large applications with ES modules, import/export syntax, and bundlers like Vite.
Named Exports
Create a file math.js:
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
// main.js
import { PI, add, multiply } from "./math.js";
console.log(add(2, 3)); // 5
Default Exports
// logger.js
export default class Logger {
log(msg) { console.log(`[LOG] ${msg}`); }
error(msg) { console.error(`[ERR] ${msg}`); }
}
// main.js
import Logger from "./logger.js"; // any name allowed
const log = new Logger();
log.log("Application started");
Re-exporting & Barrel Files
A barrel file (index.js) re-exports everything for clean imports:
// utils/index.js
export { add, multiply } from "./math.js";
export { default as Logger } from "./logger.js";
export * from "./strings.js";
// consumer.js
import { add, Logger } from "./utils"; // clean!
Dynamic import()
Load modules on demand — great for code splitting and lazy loading:
async function loadChart() {
const { drawChart } = await import("./chart.js");
drawChart(data);
}
btn.addEventListener("click", loadChart);
// chart.js is only downloaded when the button is clicked
Vite in VS 2026
Vite is the recommended bundler for modern JS projects. In VS 2026 terminal:
# Create a new Vite project
npm create vite@latest my-app -- --template vanilla
cd my-app
npm install
npm run dev
# Build for production
npm run build