Chapter 13: Modules and bundlers
This introduction traces why JavaScript module formats emerged, how developers worked around their limitations, and why ESM is becoming the standard.
After this chapter you will be able to
- Origins of competing module formats. Explain why reusable JavaScript libraries created a need for modules and why different environments adopted different formats.
- ESM adoption and advantages. Trace why ESM took time to become widely distributed and explain the current shift toward it.
- Script Tags and Globals. Explain how early JavaScript applications used ordered script tags and global variables to access libraries, and why that approach became fragile as projects grew.
- Explicit Dependency Graph. Explain how explicitly declared, build-time-parsable dependencies address ordering, missing dependencies, deferred loading, and unnecessary loading.
- Named exports and imports. Explain how a module exposes named values and how another module imports them, including renaming an import or using an export list.
- Default export naming. Distinguish a default export from named exports and explain who names a default import.
- Namespace import objects. Describe what a namespace import contains, how its properties can be changed, and when it is useful.
- Live import bindings. Explain how an imported value responds when its exporter reassigns it and why the importer cannot reassign the import.
- Runtime ownership of resolution. Explain why a valid ESM module specifier might not resolve: the ESM specification leaves interpretation of specifiers to the runtime.
- Node package entry points. Trace how Node.js resolves a bare package import through node_modules and the package's exports field, including root and subpath mappings.
- Static imports and lazy imports. Distinguish static import from import() and explain why a lazy import can avoid the parsing cost of a barrel file.
- Browser module loading timing. Explain why a browser's static import can require network loading without blocking the executing JavaScript thread, and identify which scripts enable ESM syntax.
- Browser import map resolution. Describe how a browser resolves bare specifiers using a page-defined import map and how that differs from a package's exports field.
- CommonJS module conventions. Describe how a CommonJS module exposes values through module.exports (also referenced as exports) and loads other modules with require().
- ESM and CommonJS export models. Distinguish an ESM default import from a CommonJS require() call, and explain how CommonJS code accesses an ESM module’s default export.
- Compiled CommonJS double default. Trace how TypeScript’s CommonJS compilation represents a default export and why an ESM consumer then sees a double-default problem.
- Dual vending compatibility tradeoff. Justify dual vending as a response to tooling compatibility, and describe its entry points and costs.
- Async ESM execution order. Explain how static resolution lets ESM support top-level await and how asynchronous dependencies affect module execution order.
- Dynamic CommonJS loading limit. Explain why CommonJS cannot provide the same support for async modules and what happens when require() loads an async ESM module.
- One-way interoperability constraint. Describe the practical limit top-level await places on supporting CommonJS consumers, and distinguish it from consuming CommonJS in ESM.
- Modern bundler responsibilities. Describe the kinds of work modern bundlers can perform, including analyzing module dependencies to remove dead code and create chunks, transforming modules, and preparing code for different runtimes.
- ESM loading waterfalls. Explain why fetching an ESM module graph can be slow and how bundling addresses the repeated requests.
- Page and shared chunk tradeoffs. Compare a single site-wide bundle, separate page bundles, and code splitting into shared and page-specific chunks.
- Deferred code and initial render. Explain when to lazy-load code with import() and why limiting JavaScript before rendering matters even with server-side rendering.
- Browser compatibility and transpilation. Explain why developers transpile modern JavaScript for older browsers and why they should avoid transforming more syntax than necessary.
- Baseline feature availability categories. Distinguish Baseline’s newly available and widely available categories and explain how a site’s audience affects the choice between them.
- Browserslist targets and Babel. Describe how Browserslist specifies supported browsers for build tools and how Babel uses that configuration.
- Syntax and API compatibility. Distinguish the syntax compatibility Babel provides from API compatibility and describe the check suggested for unsupported APIs.
What it builds on
- Variable scope and hoisting (chapter 7) · Uses the distinction between a variable’s scope and access from other code.
- Installing and running the TypeScript compiler (chapter 2) · Assumes familiarity with running the TypeScript compiler.
- The Node.js runtime (chapter 3) · Assumes familiarity with Node.js as a runtime.
- The perils of mutability (chapter 10) · Uses the distinction between changing an object and changing the variable that refers to it.
- Understanding node_modules (chapter 3) · Packages in node_modules
- Transpilers and polyfills give us access to tomorrow’s JavaScript today (chapter 1) · The introductory idea of transpilers making newer JavaScript usable in older environments
- Type checking with TypeScript (chapter 2) · TypeScript as a compiler for JavaScript projects
Section by section
Introduction
This introduction traces why JavaScript module formats emerged, how developers worked around their limitations, and why ESM is becoming the standard.
- Origins of competing module formats: Explain why reusable JavaScript libraries created a need for modules and why different environments adopted different formats.
Why it matters: This history explains why JavaScript packages ended up with more than one module format. - Limits of pre-ESM workarounds: Describe how browser module conventions and bundlers worked around the lack of a shared native format, and what limitation remained for build-time pruning.
Why it matters: These workarounds explain both the usefulness and the limits of older module practices. - ESM adoption and advantages: Trace why ESM took time to become widely distributed and explain the current shift toward it.
Why it matters: It explains why modern packages increasingly favor ESM without implying that CommonJS has disappeared.
Key terms: global variable, CommonJS, synchronous operation, AMD, UMD, module graph, bundler, ECMAScript Modules, ESM, dual vend
13.1 Understanding ESM
This section explains why JavaScript modules replaced script-tag dependencies and how explicit dependencies improve loading and error detection.
- Script Tags and Globals: Explain how early JavaScript applications used ordered script tags and global variables to access libraries, and why that approach became fragile as projects grew.
Why it matters: These failures explain why modules need a more explicit way to express dependencies. - Explicit Dependency Graph: Explain how explicitly declared, build-time-parsable dependencies address ordering, missing dependencies, deferred loading, and unnecessary loading.
Why it matters: Explicit dependencies make loading relationships visible before the application runs. - Unused Code Tree Shaking: Distinguish skipping an unreferenced dependency from pruning unused code within an ESM module.
Why it matters: It shows that ESM can help eliminate unused code even within a dependency that is used.
Key terms: <script> tag, global window object, indirect dependency, dependency graph, build time, deferred loading, ESM, tree-shaking
13.1.1 Importing and exporting in ESM
Explains how ESM modules expose and import values, how relative import paths work in Node.js and TypeScript, and why imports behave as live bindings.
- Named exports and imports: Explain how a module exposes named values and how another module imports them, including renaming an import or using an export list.
Why it matters: This is the basic way one ESM module makes selected values available to another. - Relative import file extensions: Explain why relative ESM imports in Node.js need explicit extensions and why TypeScript projects may use `.ts` or `.js` in those import paths.
Why it matters: An import path has to work with both the files the runtime sees and the way TypeScript checks or compiles them. - Default export naming: Distinguish a default export from named exports and explain who names a default import.
Why it matters: It prevents confusing a default value with an object containing all the module’s exports. - Namespace import objects: Describe what a namespace import contains, how its properties can be changed, and when it is useful.
Why it matters: It clarifies when to import a module’s exports together instead of selecting only the values you need. - Live import bindings: Explain how an imported value responds when its exporter reassigns it and why the importer cannot reassign the import.
Why it matters: It explains why imports reflect later changes without behaving like ordinary assignable local variables.
Key terms: export, named import, as, export list syntax, specifier, relative imports, moduleResolution, rewriteRelativeImportExtensions, default export, named exports
13.1.2 Resolving imports with entry points and maps
This section explains how Node.js and browsers resolve ESM imports, when imports load, and when import maps are useful.
- Runtime ownership of resolution: Explain why a valid ESM module specifier might not resolve: the ESM specification leaves interpretation of specifiers to the runtime.
Why it matters: It explains why the same import syntax needs different resolution arrangements in Node.js and the browser. - Node package entry points: Trace how Node.js resolves a bare package import through node_modules and the package's exports field, including root and subpath mappings.
Why it matters: It lets you reason from the import a consumer writes to the file Node.js loads. - Static imports and lazy imports: Distinguish static import from import() and explain why a lazy import can avoid the parsing cost of a barrel file.
Why it matters: It explains both where each import form can appear and why eager package-wide imports can be costly. - Browser module loading timing: Explain why a browser's static import can require network loading without blocking the executing JavaScript thread, and identify which scripts enable ESM syntax.
Why it matters: It resolves the apparent conflict between synchronous import syntax and browser network requests. - Browser import map resolution: Describe how a browser resolves bare specifiers using a page-defined import map and how that differs from a package's exports field.
Why it matters: It explains how package-like imports can work directly in browser-loaded modules. - Import maps across teams: Justify when import maps help separately bundled micro-frontends, and contrast that with a site whose bundler already rewrites imports.
Why it matters: It shows when browser-side mapping solves a coordination problem rather than duplicating the bundler's work.
Key terms: module specifiers, runtime, ESM spec, bare specifier, node_modules, package.json, exports field, package root, subpath, import
13.2 Bridging ESM with CommonJS
The section introduces how CommonJS modules export and load values, then explains why projects often need CommonJS and ESM to work together.
- CommonJS module conventions: Describe how a CommonJS module exposes values through module.exports (also referenced as exports) and loads other modules with require().
Why it matters: These conventions let you recognize what CommonJS code provides to, and requests from, other modules. - Mixed module dependency trees: Explain why ESM and CommonJS code are likely to meet in a project's dependencies, and name the two directions in which one may load the other.
Why it matters: A project can encounter both module systems through its dependencies even if it mainly uses one.
Key terms: CommonJS, module, module.exports, exports, require(), Node.js, ESM, dependencies, bundler
13.2.1 The double-default problem
This section explains why default exports behave differently across ESM and CommonJS, and how dual vending addresses the resulting compatibility problem.
- ESM and CommonJS export models: Distinguish an ESM default import from a CommonJS require() call, and explain how CommonJS code accesses an ESM module’s default export.
Why it matters: It prevents you from mistaking a module’s complete exports for its default export. - Compiled CommonJS double default: Trace how TypeScript’s CommonJS compilation represents a default export and why an ESM consumer then sees a double-default problem.
Why it matters: It explains why compiling for CommonJS compatibility can break the default-import experience for ESM users. - Dual vending compatibility tradeoff: Justify dual vending as a response to tooling compatibility, and describe its entry points and costs.
Why it matters: It shows why a package might ship two module formats despite the extra build and installation costs.
Key terms: default export, named exports, require(), module namespace object, tsc, CommonJS, default property, __esModule flag, default import, dual vending
13.2.2 The top-level await problem
Explains how top-level await changes ESM module execution and why it creates a one-way compatibility problem with CommonJS.
- Async ESM execution order: Explain how static resolution lets ESM support top-level await and how asynchronous dependencies affect module execution order.
Why it matters: It explains why awaiting at the top of an ESM module is possible without stopping all module execution. - Dynamic CommonJS loading limit: Explain why CommonJS cannot provide the same support for async modules and what happens when require() loads an async ESM module.
Why it matters: It identifies the specific boundary that prevents CommonJS consumers from loading ESM modules that use top-level await. - One-way interoperability constraint: Describe the practical limit top-level await places on supporting CommonJS consumers, and distinguish it from consuming CommonJS in ESM.
Why it matters: It helps you decide whether top-level await fits a module that must serve CommonJS users.
Key terms: top-level await, ESM dependency tree, async modules, CommonJS, require(), static dependency analysis, async ESM module, dual vending, CommonJS consumers, TypeScript
13.3 Building JS bundles
This section explains why JavaScript bundlers emerged, what modern bundling tools can do, and how a build orchestrator differs from a bundler.
- Modern bundler responsibilities: Describe the kinds of work modern bundlers can perform, including analyzing module dependencies to remove dead code and create chunks, transforming modules, and preparing code for different runtimes.
Why it matters: It gives you a useful picture of what a modern JavaScript build tool may do before code reaches users. - Evolution of JavaScript builds: Explain why web development moved from shipping scripts as written to minifying and concatenating them, and then to dependency-aware bundlers.
Why it matters: The history explains which problems bundlers grew out of. - Bundlers and build orchestrators: Distinguish a bundler from a build orchestrator using the section’s Vite example.
Why it matters: This distinction helps you interpret what developers mean when they name their project’s “bundler.”
Key terms: bundlers, module graph, dead code, chunks, transpiling, minifiers, HTTP request overhead, CommonJS, bundler, Vite
13.3.1 The art of code splitting
The section explains how code splitting reduces JavaScript loading costs by delivering the chunks a page needs when it needs them.
- ESM loading waterfalls: Explain why fetching an ESM module graph can be slow and how bundling addresses the repeated requests.
Why it matters: This explains the network cost that bundling and code splitting are meant to manage. - Page and shared chunk tradeoffs: Compare a single site-wide bundle, separate page bundles, and code splitting into shared and page-specific chunks.
Why it matters: Chunk boundaries determine how much code visitors download before the first page and when they navigate. - Chunk-level cache benefits: Explain how splitting frequently changed page code from shared code affects repeat visits.
Why it matters: Splitting code can reduce downloads after updates, not just on a visitor’s first trip through the site. - Strategic chunk preloading: Describe how manual splitting and early chunk downloads can improve a chosen navigation path, and distinguish modulepreload from prefetching in the examples.
Why it matters: Choosing when chunks start downloading can avoid waits even when the code is split well. - Deferred code and initial render: Explain when to lazy-load code with import() and why limiting JavaScript before rendering matters even with server-side rendering.
Why it matters: Deferring nonessential code keeps the first render lighter without overlooking the JavaScript needed for interaction. - Bundle visualization for bloat: Describe how visualizing a bundle helps identify JavaScript to remove, split, or lazy-load.
Why it matters: Inspecting what is actually in a bundle helps target loading optimizations.
Key terms: ESM, module graph, round trip, loading waterfall, bundler, code splitting, chunk, shared code, page bundle, browser’s cache
13.3.2 Targeting browsers with transpilation
Explains how to choose browser compatibility targets, transpile JavaScript for them, and recognize the limits and costs of that approach.
- Browser compatibility and transpilation: Explain why developers transpile modern JavaScript for older browsers and why they should avoid transforming more syntax than necessary.
Why it matters: A compatibility target should protect the browsers you support without needlessly increasing download size. - Baseline feature availability categories: Distinguish Baseline’s newly available and widely available categories and explain how a site’s audience affects the choice between them.
Why it matters: Baseline gives you a way to choose features based on how current your audience’s browsers are likely to be. - Browserslist targets and Babel: Describe how Browserslist specifies supported browsers for build tools and how Babel uses that configuration.
Why it matters: This connects a project’s browser-support decision to the syntax its build emits. - Syntax and API compatibility: Distinguish the syntax compatibility Babel provides from API compatibility and describe the check suggested for unsupported APIs.
Why it matters: Code can have valid syntax in a target browser yet still fail when it calls an unavailable API. - TypeScript and Babel targeting: Explain why TypeScript’s ECMAScript target is a coarse browser-compatibility setting and describe the finer-grained approach in this section.
Why it matters: Separating TypeScript’s output target from browser-specific transpilation avoids relying on a single coarse ECMAScript version.
Key terms: Babel, transpile, ES5, syntax, Baseline, newly available, widely available, Browserslist, package.json, preset-env
13.4 Summary
Concepts explained in this chapter
- import statementThe import keyword statically declares dependencies on exported bindings from other ECMAScript modules.
- ECMAScript moduleA JavaScript module whose dependencies and shared bindings are declared using standardized import and export syntax.
- default exportA module export designated as the value available through a default import.
- module namespace objectAn object that exposes a module’s exported bindings as properties.
- live bindingA live binding is an imported reference to an exported variable whose current value reflects subsequent reassignment by the exporting module.
- named exportA named export is a module export identified by a name that importers can reference explicitly.
- entry pointA package entry point is a file path that a package exposes as the target of an import specifier.
- import mapAn import map is a JSON mapping that associates JavaScript module specifiers with URLs or paths.
- export keywordThe export keyword declares bindings or values that other modules can import.
- named importA named import brings a specific named export into another module, optionally under a local alias.
- namespace importA namespace import binds a module's exported names together as properties of an imported namespace object.
- module graphA graph representing modules as nodes and their import dependencies as directed edges.
- CommonJSCommonJS is a JavaScript module-system specification traditionally based on synchronous require calls and module.exports assignments.
- transpilationThe transformation of source code from one programming-language syntax or level of abstraction into another while preserving its behavior.
- code splittingA build technique that divides application code into separate output chunks, often so they can be loaded independently.
- bundlerA build tool that combines source modules and their dependencies into distributable output files.
- loading waterfallA sequence of resource downloads in which each newly discovered dependency must be fetched before further dependencies can be requested.
- tree-shakingTree-shaking is a build-time optimization that removes unused code from a program by analyzing its module dependencies and exports.
- dependency graphA graph representing dependencies among components of a software project.
- default importAn import that binds a module's default export to a local name.
- dynamic importDynamic import is an expression that loads a module at runtime and returns a promise for its module namespace object.
- bare specifierA bare specifier is a module import specifier expressed as a package name rather than a relative or absolute file path.
- dependency treeA hierarchical representation of a package's direct and transitive dependencies.
- exports fieldThe exports field is a package.json field that defines which package subpaths and entry points can be imported.
- lazy initializationDeferred loading is the postponement of loading a dependency until it is needed or otherwise appropriate.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
