Skip to content

Modules and Bundling ​

Describe what a bundler does in four steps, and explain why one import pulled in half a library.

In this chapter: the four steps · resolution and bare specifiers · the module graph · chunking as graph partitioning · why ESM made this possible · source maps

💡 The Core Idea ​

A bundler does four things, in order:

Resolve — turn every import specifier into a file on disk. Load and transform — read each file and convert it to something a browser understands. Build a graph — follow the imports until nothing new is reachable. Emit chunks — partition that graph into files and write them out.

Almost every bundler problem is one of those four steps failing. Often the error message names a different step. "Module not found" is resolution. "Unexpected token" is transformation. "Why is this in my bundle?" is the graph. "Why are there forty chunks?" is emission.

Name the step first, and a two-hour build investigation becomes a ten-minute one.

How It Works ​

The four steps ​

Resolution and loading loop until the graph closes; emission happens once.

Resolution, and why bare specifiers are hard ​

./utils is a relative path. The resolver adds extensions until it finds a file. react is a bare specifier, and browsers have no rule for it. The bundler has to walk up the directory tree looking in node_modules. Then it reads that package's package.json to decide which file it actually means.

That last part causes most resolution surprises, because a package can declare several entry points for one import:

FieldChosen when
exportsModern resolvers, and it overrides everything else
mainLegacy fallback, usually CommonJS
moduleOlder convention for an ESM build
browserA browser-specific substitution
Conditions inside exportsimport / require / node / browser / development

An exports map is also a wall: you cannot import a file it does not list. So a deep import that worked last year can fail after a dependency upgrade. That is not a bug in your build. The package author has closed a door they never meant to leave open.

The graph decides what ships ​

Once resolution succeeds, the bundler follows imports transitively. Everything reachable from an entry point is in the bundle. Reachable, not used: those are different, and bundle weight comes from the difference.

A barrel file (an index.ts that re-exports a folder) is the usual culprit:

typescript
// components/index.ts — re-exports forty components
export * from './Button';
export * from './DataGrid'; // pulls in a charting dependency
// ...

// Somewhere else — this reaches the whole barrel before anything is eliminated.
import { Button } from '../components';

Removing what is reachable but unused is tree shaking. It needs static imports and honest side-effect metadata to work. The mechanics are in Loading, Code Splitting and Bundle Budgets. What matters here: the bundler builds the graph first and prunes it second. A graph that reaches too far limits how much pruning can help.

Why ESM changed what was possible ​

CommonJS is resolved at runtime. require() is a function call, its argument can be computed, and exports can be reassigned while the program runs. A bundler cannot know what a CommonJS module exports without executing it.

ES modules are statically analysable. Imports and exports are hoisted declarations with fixed names, resolved before any code runs. That makes tree shaking, safe cross-module inlining and reliable chunking possible at all. It is also why every tool in this section assumes ESM and treats CommonJS as a compatibility case.

Chunking is graph partitioning ​

Emitting one file per module means hundreds of requests. Emitting one file means downloading the whole application to see the login page. Chunking is the compromise. It is a real optimisation problem with three competing goals:

GoalPulls towards
Fewer requestsLarger chunks
Less unused code per routeSmaller chunks
Better cache reuse across deploysStable boundaries between rarely- and frequently-changing code

People forget the third goal. Say a shared chunk holds both your dependencies and your application code. Then every deploy invalidates the dependencies too, and returning users re-download a library that did not change.

Two chunk boundaries exist without you asking. A dynamic import, such as import('./Editor'), is always a split point, because nothing needs its target until the call. And most bundlers separate node_modules from source, for the caching reason above. Everything beyond that is configuration, covered as a performance technique in Loading, Code Splitting and Bundle Budgets.

Source maps, and what they cost ​

A source map maps positions in the emitted file back to your source. Without one, a production stack trace points at column 41,209 of main-a3f9.js.

The decision is not whether to generate them but where they live:

OptionDebuggable in productionSource visible to users
Inline in the bundleYesYes — and the bundle is much larger
Separate file, publicly servedYesYes, to anyone who looks
Separate file, uploaded to error tracking onlyYes, in the error toolNo
NoneNoNo

The third row is the answer for most products: generate maps, upload them to the error reporter during the build, and do not deploy them to the CDN.

When to Use It ​

You do not choose whether to bundle any more. Every framework ships a bundler. What you do choose:

DecisionGuidance
Barrel files in application codeAvoid. Import from the module that defines the thing
Barrel files in a published packageOnly with sideEffects: false and per-file exports
Manual chunk configurationOnly after reading a bundle report. Defaults are good now
Bundling a library you publishShip ESM, declare exports and sideEffects, do not bundle dependencies
Source mapsAlways generate; upload to error tracking, do not serve publicly

Common Mistakes ​

❌ Importing from a barrel to keep import lines tidy. ✅ It reaches the whole barrel. Import from the defining module.

❌ Assuming an unused import is free. ✅ It is free only if the module has no side effects and the package says so. Otherwise it ships.

❌ Deep-importing into a package's internals. ✅ An exports map can remove that path in a patch release. Use the public entry points.

❌ Reading a bundle size total and stopping there. ✅ The total says nothing about which route pays for what. Read the per-chunk report and the module attribution inside the largest chunk.

❌ Publishing source maps to the CDN because the build produced them. ✅ That publishes your source. Upload them to the error tracker instead.

🔑 Key Takeaways ​

  • A bundler resolves, transforms, builds a graph, and emits chunks. Its errors usually name the wrong step.
  • A package's exports map decides which file an import means, and forbids everything it does not list.
  • Everything reachable from an entry point ships. Reachable is not the same as used.
  • ES modules are statically analysable, which is what makes tree shaking and reliable chunking possible.
  • Chunking trades request count against unused code against cache reuse across deploys.

Interview Questions ​

Q: What does a bundler actually do?

Four steps. It resolves each import specifier to a file, applying the package's exports conditions for bare specifiers. It loads and transforms each file: TypeScript, JSX, CSS. It follows imports to build a module graph. Then it partitions that graph into chunks and emits them with source maps. Most build failures are one of those four steps, and the error message often names a different one.

Q: A single import added 300 KB to the bundle. How do you find out why?

Read the bundle report for module attribution inside the chunk that grew, and trace the import path back to your source. The usual answer is a barrel file. Import one component from an index that re-exports forty, and you reach all forty. Tree shaking cannot remove modules that the package has not declared side-effect-free. The fix is to import from the defining module.

Q: Why did tree shaking only become practical with ES modules?

CommonJS resolves at runtime. require() takes any expression, and code can reassign exports. So a bundler cannot know what a module exports without running it. ESM imports and exports are static declarations with fixed names, resolved before execution. So the tool can prove a binding is never read and delete it.

Q: How would you decide where to split chunks?

Start from the defaults: dynamic imports and a vendor split. Then look at what a returning user re-downloads after a deploy. If application code and dependencies share a chunk, every release invalidates both. Separate code by change rate, not by feature. Only tune further with a bundle report in front of you.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.