Module Bundlers: Webpack, Parcel & Vite
Published by Brayan K
Master the tools that power modern JavaScript development. Learn bundling, code splitting, tree shaking, HMR, and production optimization across Webpack, Vite, and Parcel.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Modules define dependencies; build tools prepare an application
An import describes a dependency. A build tool resolves a graph of those dependencies and prepares code and assets for a chosen runtime. A development server may serve modules differently from the production build. A working development page therefore does not prove that the deployed asset paths, deferred chunks or compatibility settings are correct.
// This real embedded module needs no server or bundler.
const moduleURL = "data:text/javascript," + encodeURIComponent("export const total = 9;");
const pending = import(moduleURL);
console.log(typeof pending.then);
// Await the namespace before reading its export.
const module = await pending;
console.log(module.total);
// ✅ Expected output:
// function
// 9This example demonstrates the browser import operation, not a production chunk or downloaded byte saving. JavaScript Modules: ES6 Imports, Exports, Bundling owns module syntax and evaluation. The fixture below uses a real production build to check the separate bundler behavior.
Use each tool’s project contract instead of mixing configuration dialects
Webpack exposes an explicit configuration and loader/plugin ecosystem. Parcel begins from entries and handles many asset transformations by convention. Vite combines a development server with a production build pipeline. Their configuration files and plugin interfaces are not interchangeable, and implementation details change across major versions. Use the documentation matching the version in your lockfile.
For a new Vite project, follow its current setup guide and supported Node requirements. Within that project, keep distinct dev, build and preview scripts. Build creates production artifacts; preview serves those artifacts for local checking and is not a production hosting service. The checked fixture uses the repository’s installed Vite, with no claim that it is the newest release.
Commit the dependency manifest and lockfile together. A build command that succeeds on a machine with unrecorded global tools is not a reproducible project setup. The practical unit to review is source plus configuration plus dependencies plus the resulting artifacts.
A complete build fixture makes the emitted behavior reviewable
Create the following four files in one Vite project. The page has one initial state and a button-triggered report. The checked build uses a /practice/ public base to exercise nested asset paths. Its output panel shows the actual visible text before and after activating the button.
index.html — bundle fixture
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Lazy report fixture</title><link rel="icon" href="data:,"></head>
<body><button id="load" type="button">Calculate total</button><output id="result" aria-live="polite">Ready</output>
<script type="module" src="/src/main.js"></script></body></html>Output
Ready
Total: 9These files form one Vite project. Run the development/build commands in that project; they are not independent snippets for the single-file editor.
src/main.js — bundle fixture
import { sum } from "./math.js";
const button = document.getElementById("load");
const result = document.getElementById("result");
button.addEventListener("click", async () => {
button.disabled = true;
result.textContent = "Loading";
try {
const { format } = await import("./format.js");
result.textContent = format(sum([2, 3, 4]));
result.dataset.status = "complete";
} catch {
result.textContent = "Could not load report";
result.dataset.status = "failed";
} finally { button.disabled = false; }
});These files form one Vite project. Run the development/build commands in that project; they are not independent snippets for the single-file editor.
src/math.js — bundle fixture
globalThis.fixtureEvaluations = (globalThis.fixtureEvaluations || 0) + 1;
export const sum = values => values.reduce((total, value) => total + value, 0);
export const unusedText = "LCS_UNUSED_PURE_EXPORT_MARKER";These files form one Vite project. Run the development/build commands in that project; they are not independent snippets for the single-file editor.
src/format.js — bundle fixture
export const format = value => "Total: " + value;These files form one Vite project. Run the development/build commands in that project; they are not independent snippets for the single-file editor.
The build check found a separate deferred formatter chunk, confirmed it was not requested before activation, then loaded it and checked the result. It also confirmed that the unused pure export marker was absent from emitted JavaScript while the module evaluation effect still ran once. No exact file hash, chunk count, byte size or speedup is promised; those depend on source, configuration and tool versions.
Tree shaking cannot discard an observable effect merely because an export is unused
globalThis.bundleLessonEffects = [];
const url = "data:text/javascript," + encodeURIComponent(
'globalThis.bundleLessonEffects.push("evaluated"); export const unused = 7;'
);
await import(url);
console.log(globalThis.bundleLessonEffects.join(","));
delete globalThis.bundleLessonEffects;
// ✅ Expected output:
// evaluatedThe fixture’s unused string export is safe to remove; its top-level counter update is an effect that must remain. Marking an entire package sideEffects:false is a promise about its files, not a general “make this smaller” switch. Incorrect metadata can remove required CSS or initialization. Inspect the emitted behavior and test the production page after changing it.
Minification shortens or transforms code; compression changes how bytes are transferred. Neither makes client secrets private, and syntax transpilation does not automatically provide every missing runtime API. Choose browser targets and any required polyfills deliberately. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns public client-code trust boundaries.
A split chunk needs loading, failure and deployment behavior
const trace = [], url = "data:text/javascript," + encodeURIComponent(
'export const format = value => "Total: " + value;'
);
trace.push("loading");
const module = await import(url);
trace.push(module.format(9));
console.log(trace.join(" | "));
// ✅ Expected output:
// loading | Total: 9A production dynamic import can fail because of a network problem, a stale HTML document naming a removed chunk, a deployment base mismatch or module evaluation failure. Show a recoverable failure state and keep the user’s input where possible. Retrying the same failed import URL is not uniformly recoverable across browser versions; a documented refresh path may be needed.
const states = [];
async function activate(load) {
states.push("loading");
try { const module = await load(); states.push(module.format(9)); }
catch { states.push("failed"); }
}
await activate(async () => { throw new Error("fixture load failure"); });
console.log(states.join(","));
// ✅ Expected output:
// loading,failedThis injected failure tests application feedback; it does not measure a real network. Dynamic import is a loading boundary, not a guarantee that every tool emits one extra file. Inspect the production manifest or chunks, check requests before and after the interaction, and verify that deployment preserves the referenced assets.
Source maps and public environment values are part of what ships
const configuration = { publicLabel: "Demo", serviceSecret: "do-not-bundle" };
console.log(Object.keys(configuration).join(","));
// ✅ Expected output:
// publicLabel,serviceSecretRenaming or minifying this object does not turn the second value into a protected server secret. Source maps can make debugging easier and may expose original source; decide where to publish them according to the application. Review build-time substitutions and deployed assets instead of assuming that a variable’s environment-based origin makes it private.
Test the built page with its actual public base, a direct route load and an older page open during a new deployment. Deploying JavaScript Apps (CDN, Minification, Bundling) owns the broader hosting and cache rollout contract. No deployment is performed by this lesson’s offline build fixture.
Guided exercise: use the loaded namespace after awaiting it
Fill the literal hints. This real embedded module runs in the editor; the project fixture is the place to inspect actual emitted chunks.
const url = "data:text/javascript," + encodeURIComponent('export const format = value => "Total: " + value;');
const module = ___ import(url); // 👉 replace ___ with await
console.log(module.___(9)); // 👉 replace ___ with format
// ✅ Expected output:
// Total: 9Independent brief: a lazy report with an honest failure state
Implement mountLazyReport(root, load). Require an empty HTMLElement and a loader function returning a module with a synchronous format(number) function that returns text. Mount a native button and live output. Return run() and idempotent dispose(). run reports complete, failed, busy or disposed, disables duplicate activation while loading, and caches only a successful validated module.
Show Ready initially, Loading while pending, the formatted result on success and Could not load report on failure. A later run may call a failed injected loader again; do not claim that this guarantees a browser can refetch the same failed module URL. After disposal, no pending result may repopulate the container. This controller exercises UI loading policy; the four-file Vite fixture verifies actual production splitting.
function mountLazyReport(root, load) {
if (!(root instanceof HTMLElement) || root.childNodes.length || typeof load !== "function")
throw new TypeError("an empty root and loader function are required");
const button = document.createElement("button"), output = document.createElement("output");
button.type = "button"; button.textContent = "Load report";
output.setAttribute("aria-live", "polite"); output.textContent = "Ready";
root.append(button, output);
let active = true, busy = false, cached = null;
async function run() {
if (!active) return "disposed";
if (busy) return "busy";
busy = true; button.disabled = true; output.textContent = "Loading";
try {
const module = cached ?? await load();
if (!active) return "disposed";
if (!module || typeof module.format !== "function") throw new TypeError("module must export format");
const text = module.format(9);
if (typeof text !== "string") throw new TypeError("format must return text");
if (!active) return "disposed";
cached = module; output.textContent = text;
return "complete";
} catch {
if (!active) return "disposed";
output.textContent = "Could not load report";
return "failed";
} finally {
busy = false;
if (active) button.disabled = false;
}
}
const click = () => { void run(); };
button.addEventListener("click", click);
return Object.freeze({
run,
dispose() {
if (!active) return false;
active = false; cached = null;
button.removeEventListener("click", click); button.remove(); output.remove();
return true;
}
});
}
const root = document.createElement("section"); document.getElementById("app").append(root);
let calls = 0;
const moduleURL = "data:text/javascript," + encodeURIComponent('export const format = value => "Total: " + value;');
const report = mountLazyReport(root, async () => {
if (++calls === 1) throw new Error("fixture failure");
return import(moduleURL);
});
console.log(await report.run(), root.querySelector("output").textContent);
console.log(await report.run(), root.querySelector("output").textContent);
console.log(await report.run(), calls);
report.dispose();
let release;
const late = mountLazyReport(root, () => new Promise(resolve => { release = resolve; }));
const pending = late.run();
console.log(await late.run());
late.dispose(); release({ format: value => "late " + value });
console.log(await pending, root.childNodes.length);
// ✅ Expected output:
// failed Could not load report
// complete Total: 9
// complete 2
// busy
// disposed 0Tool documentation
Use the version-appropriate Vite build guide, webpack tree-shaking guide and Parcel production guide. The measured fixture checks Vite only; it does not claim equivalent webpack or Parcel execution.
Practice quiz
What does this complete program print? const url="data:text/javascript,"+encodeURIComponent("export const value=7;");const pending=import(url);console.log(typeof pending.then,(await pending).value);
- function 7
- undefined 7
- function undefined
- number 7
Answer: function 7. A dynamic import returns a promise for the module namespace.
What does this complete program print? const url="data:text/javascript,"+encodeURIComponent("export const value=7;");const a=await import(url),b=await import(url);console.log(a===b);
- false
- true
- undefined
- TypeError
Answer: true. The same module URL is cached within this module environment.
What does this complete program print? const states=[];try{states.push("loading");await Promise.reject("fixture")}catch{states.push("failed")}console.log(states.join(","));
- loading
- failed
- loading,failed
- loading,complete
Answer: loading,failed. The failure path remains visible instead of pretending success.
What does this complete program print? let creates=0,module;const load=()=>{creates++;return {value:1}};module??=load();module??=load();console.log(creates);
- 0
- 2
- undefined
- 1
Answer: 1. A successfully cached module value avoids a second loader invocation.
Which result was measured by the four-file fixture?
- A deferred formatter chunk was requested only after activation
- Every bundler is equally fast
- All builds produce exactly two files
- The application is deployed
Answer: A deferred formatter chunk was requested only after activation. The fixture checks its real Vite artifacts and browser requests, not universal performance.
Why can incorrect sideEffects:false metadata break an application?
- It encrypts source files
- It may allow required initialization or styles to be removed
- It prevents all imports
- It changes every URL to HTTPS
Answer: It may allow required initialization or styles to be removed. Side-effect metadata is a semantic promise that affects what a bundler may remove.
What does minification establish about a bundled secret?
- It is inaccessible to users
- It is safely encrypted
- It remains shipped client data despite harder-to-read names
- It is moved to a server
Answer: It remains shipped client data despite harder-to-read names. Client-shipped data is not made private by minification.
Why check the production page under its real public base?
- Development and production always use identical paths
- It guarantees all browsers support every API
- It eliminates the need for a lockfile
- Asset and deferred-chunk URLs may fail under a nested deployment path
Answer: Asset and deferred-chunk URLs may fail under a nested deployment path. The built artifact and deployment base need to agree.
Continue this course
- Previous: Building Reusable UI Components with Pure JS
- Next: Intro to TypeScript & Strong Typing Concepts — Add static types to JavaScript with TypeScript and avoid runtime bugs
- Quick reference: JavaScript cheat sheet