Bundlers and Transpilers: Vite, esbuild, Rollup, webpack, Babel and TypeScript Compilation
What happens between your source and the code users download: why bundling still matters, module graphs, tree-shaking, code splitting, minification, source maps, dev servers and HMR, transpiling with Babel, esbuild and TypeScript, targets and polyfills.
kvi5hnuCode Sprout team member8 min readOn this page
Browsers have supported ES modules natively for years (article 76), so you can ship a web app as a set of .js files with import statements. Most production sites still run their code through a build step first. This article explains what that step does and the tools that do it.
Why bundle?
- Fewer, smaller requests. A large app may have thousands of modules, including those inside
node_modules. Loading each separately means long chains of requests: the browser only discovers a module's imports after downloading it. A bundler combines them into a few optimized files. - Less code. Bundlers drop unused code and minify the rest. Code size is the one performance variable you fully control: less JavaScript always downloads, parses and runs faster.
- Packages and non-JavaScript imports. Bundlers resolve bare imports like
import { format } from "date-fns"to files innode_modules, and handle imports of CSS, JSON, images, TypeScript and JSX. - Caching. Output files get content hashes in their names (
app-3f9a.js), so browsers can cache them forever and fetch a new name only when the content changes.
What a bundler does

A bundler starts from one or more entry points, follows every import to build the module graph, and emits code in which each module's imports are wired to the right exports. This toy version shows the principle:
// A toy bundler: follow imports from an entry file, wrap each module in a
// function, and emit one script with a tiny module loader.
const lines = (...l) => l.join("\n");
const files = {
"./main.js": lines(
'import { add, multiply } from "./math.js";',
'import { formatPrice } from "./format.js";',
"const total = add(multiply(1250, 2), 399);",
"console.log(formatPrice(total));"),
"./math.js": lines(
"export function add(a, b) { return a + b; }",
"export function multiply(a, b) { return a * b; }"),
"./format.js": lines(
'import { add } from "./math.js";',
'export const formatPrice = (cents) => "$" + add(0, cents / 100).toFixed(2);'),
};
// Rewrite import/export syntax into calls the loader understands
function transform(source) {
const deps = [];
const code = source
.replace(/^import \{([^}]+)\} from "([^"]+)";$/gm, (_, names, from) => {
deps.push(from);
return `const {${names}} = require("${from}");`;
})
.replace(/^export (?:function|const) (\w+)/gm, (match, name) => {
deps.exportNames = [...(deps.exportNames ?? []), name];
return match.replace("export ", "");
});
const exportsLine = (deps.exportNames ?? []).map((n) => `exports.${n} = ${n};`).join(" ");
return { deps, code: `${code}\n${exportsLine}` };
}
function bundle(entry) {
const modules = new Map();
const visit = (path) => { // depth-first walk of the import graph
if (modules.has(path)) return; // each module is included once
const { deps, code } = transform(files[path]);
modules.set(path, code);
deps.forEach(visit);
};
visit(entry);
const table = [...modules].map(([path, code]) =>
`${JSON.stringify(path)}: function (require, exports) {\n${code}\n}`).join(",\n");
return `const modules = {\n${table}\n};
const cache = {};
function require(path) {
if (!cache[path]) { cache[path] = {}; modules[path](require, cache[path]); }
return cache[path];
}
require(${JSON.stringify(entry)});`;
}
const output = bundle("./main.js");
console.log("modules in bundle:", [...output.matchAll(/^"(\.\/\w+\.js)": function/gm)].map((m) => m[1]));
console.log("format.js after transform:\n" + transform(files["./format.js"]).code);
new Function(output)(); // run the single-file bundle
modules in bundle: [ './main.js', './math.js', './format.js' ]
format.js after transform:
const { add } = require("./math.js");
const formatPrice = (cents) => "$" + add(0, cents / 100).toFixed(2);
exports.formatPrice = formatPrice;
$28.99
It walks the graph depth-first, includes each module once even though two modules import math.js, rewrites import/export into calls to a tiny loader, and produces a single script. Real bundlers parse code properly instead of using regular expressions, and they can usually hoist everything into one scope rather than wrapping modules in functions. Here's what esbuild produces for a similar three-module project, with esbuild src/main.js --bundle --format=esm:
// src/math.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
// src/format.js
var formatPrice = (cents) => "$" + (cents / 100).toFixed(2);
// src/main.js
var cart = [{ price: 1250, qty: 2 }, { price: 399, qty: 1 }];
var total = cart.reduce((sum, item) => add(sum, multiply(item.price, item.qty)), 0);
console.log(formatPrice(total));
math.js also exported an unusedHelper function that nothing imports, and it's gone. That's tree-shaking: static import/export declarations (article 75) let the bundler see exactly which exports are used. Code with side effects at module load prevents this, which is why libraries mark themselves "sideEffects": false in package.json when they can. With --minify, the same bundle shrinks to one line with short names:
function e(r,t){return r+t}function o(r,t){return r*t}var n=r=>"$"+(r/100).toFixed(2);var c=[{price:1250,qty:2},{price:399,qty:1}],i=c.reduce((r,t)=>e(r,o(t.price,t.qty)),0);console.log(n(i));
Other bundler features:
- Code splitting: each dynamic
import()(article 76) becomes a separate chunk that loads only when needed, such as a chart library on the reports page. Shared code goes into common chunks. - Source maps:
.mapfiles map the bundled, minified code back to your original files and lines, so stack traces and the browser debugger show real source. Generate them for production too, even if you don't serve them publicly. - Asset handling: imported CSS is extracted into
.cssfiles; images get hashed names; small files may be inlined. - Environment replacement:
import.meta.env.MODEorprocess.env.NODE_ENVis replaced with a constant, so development-only code is removed entirely from production builds.
Development servers
Rebuilding a full bundle on every edit is slow in a large app. Vite, today's most popular front-end build tool, serves your source as native ES modules during development, transforming each file on demand, and uses hot module replacement (HMR) to swap changed modules into the running page without a full reload, keeping application state. For production, it runs a full optimized build. Starting a project takes one command: npm create vite@latest.
The bundlers you'll meet
| Tool | Notes |
|---|---|
| Vite | dev server plus production builds; Vite 8 builds with Rolldown, a Rust bundler with a Rollup-compatible plugin API; the default for new React, Vue, Svelte and vanilla projects |
| esbuild | written in Go, extremely fast; great for libraries, servers and scripts; used inside many other tools |
| Rollup | the classic ES-module bundler, ideal for libraries; its plugin API lives on in Vite and Rolldown |
| webpack | the long-time standard: hugely configurable, huge plugin ecosystem; still common in older and enterprise apps |
| Rspack, Turbopack, Parcel | Rspack is a fast webpack-compatible bundler in Rust; Turbopack is Next.js's bundler; Parcel aims for zero configuration |
Frameworks such as Next.js, Nuxt, SvelteKit and Astro configure all of this for you. For server-side Node code, a bundler is often unnecessary: Node runs ES modules, and even TypeScript (article 122), directly.
Transpilers
A transpiler compiles JavaScript (or a JavaScript-like language) into JavaScript. It has three jobs today:
- Remove language extensions: TypeScript type annotations (article 138) and JSX (article 137) aren't JavaScript, so they must be compiled away before anything can run them.
- Downlevel new syntax for older target environments. With
--target=es2019, esbuild rewrites newer syntax:
// input
const dark = settings.theme?.dark ?? false;
// esbuild output for an ES2019 target
var _a, _b;
const dark = (_b = (_a = settings.theme) == null ? void 0 : _a.dark) != null ? _b : false;
Private class fields become WeakMaps plus helper functions, and the output gets longer and harder to read; source maps make that bearable.
3. Minify, as shown earlier.
Transpilers transform syntax only. A missing API, such as Array.prototype.findLast or Promise.try in an old browser, needs a polyfill: a library that adds the missing function at run time (core-js is the standard one). Transpiling down to ES5 is rarely needed anymore. Modern tools default to targets like "Baseline widely available" browsers, which support almost all of ES2020+, so less code is transformed and bundles stay small.
The main transpilers:
- Babel was the original, created so developers could write ES6 before browsers supported it. It's written in JavaScript, configured with presets such as
@babel/preset-env(target browsers) and@babel/preset-react, and is the most extensible, with plugins for experimental proposals. Babel 8 is the current major version. - esbuild and SWC (Rust) do the same transformations 10 to 100 times faster with less configurability, and most modern tools use one of them internally.
- TypeScript's compiler,
tsc, can also emit JavaScript, but in many projects it only type-checks (tsc --noEmit), while a faster tool strips the types. TypeScript 7 replaced the JavaScript-based compiler with a native port written in Go, roughly 10 times faster.
The pieces connect: the bundler calls the transpiler on each file as it builds the graph, so you rarely run Babel or esbuild on their own.
Common questions
Do I still need a bundler if browsers support ES modules?
For anything beyond a small site, usually yes: bundling reduces requests, removes unused code, handles npm packages and other assets, and adds content hashes for caching. For small pages, plain modules (with an import map for packages) work fine.
What's the difference between transpiling and polyfilling?
Transpiling rewrites syntax, such as ?., classes or JSX, at build time. Polyfilling adds missing built-in functions, such as Array.prototype.at, at run time. Old browsers may need both.
Vite, webpack or esbuild?
For a new web app, Vite (or a framework built on it). For bundling a library or a Node service, esbuild, Rolldown or Rollup. Keep webpack where it's already working; migrate when its speed or complexity becomes a problem.
Summary
- Bundlers follow imports from entry points to build a module graph, include each module once, tree-shake unused exports, split dynamically imported code into chunks, minify, add hashed file names and emit source maps.
- Vite serves unbundled modules with hot module replacement in development and runs an optimized build for production; esbuild, Rollup/Rolldown and webpack are the other major bundlers.
- Transpilers (Babel, esbuild, SWC,
tsc) compile away TypeScript and JSX, downlevel new syntax for older targets and minify; polyfills supply missing APIs.
Practice Questions
Why can a bundler tree-shake import { add } from "./math.js", but not const math = require("./math.js")?
Answer
ES module imports and exports are static declarations, so the bundler knows at build time exactly which exports are used and can drop the rest. With CommonJS, require is an ordinary function call returning an object whose properties can be accessed dynamically, so the bundler can't safely tell which parts are unused.
A site must support an old browser without optional chaining or Array.prototype.at. What does the build need for each?
Answer
Optional chaining is syntax, so the transpiler must downlevel it for that target. Array.prototype.at is a built-in method, so the page needs a polyfill, for example from core-js, that adds it at run time.
How would you make a heavy charting library load only when the user opens the reports page?
Answer
Import it dynamically where it's needed, for example const { Chart } = await import("chart-lib") in the reports page's code. The bundler splits it into a separate chunk that's downloaded on first use.
Previous: Package Management: npm, package.json, Semantic Versioning and Lockfiles
Next: JSX: Markup Expressions in JavaScript, and What They Compile To

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.