Sub topic 2
Dynamic import() and chunks
This chapter covers how import() lets a bundler split code into chunks. It assumes you know ES modules, promises, and have used a bundler such as Vite or webpack. The next chapter uses this mechanism through React.lazy.
Static import versus dynamic import
A static import statement sits at the top of a file. The bundler reads it at build time and includes the imported module in the same output file as the importer.
import { formatDate } from './format.js';A dynamic import() is an expression that you can call anywhere, such as inside a function or an event handler. It takes a module path and returns a promise. The promise resolves to the module's namespace object.
const module = await import('./format.js');
console.log(module.formatDate(new Date()));Because the call runs at runtime, the browser fetches the module only when the call executes. Nothing is downloaded before that.
What a chunk is
A chunk is a separate JavaScript file that the bundler produces from your source. When the bundler sees import('./format.js') with a string literal path, it treats that module as a split point. It puts the module, and any dependencies not already shared, into its own chunk.
The main bundle keeps a small piece of loader code. When import() runs, that code requests the chunk file over the network, runs it, and resolves the promise.
A runnable example
This example loads a heavy module only when the user clicks a button. Assume report.js exists and exports a function named buildReport.
// report.js
export function buildReport(rows) {
return rows.map((row) => row.join(',')).join('\n');
}// main.js
const button = document.querySelector('#export');
button.addEventListener('click', async () => {
const { buildReport } = await import('./report.js');
const csv = buildReport([['id', 'name'], [1, 'Ada']]);
console.log(csv);
});Build this with Vite or webpack and look at the output. You will see report.js in its own file, with a hashed name such as report-3f9a1c.js. Open the browser's Network tab. The file does not appear until the first click.
Behavior to know
- The promise is cached. The module runs once. A second
import('./report.js')resolves with the same module object and does not fetch again. - Default exports live under
default. The resolved object has the shape{ default: ..., namedExport: ... }. This is whyReact.lazyneeds the module's default export, which later chapters cover. - The path must be analyzable. A literal string such as
'./report.js'lets the bundler find the module at build time. A fully dynamic path such asimport(userInput)cannot be split at build time. Bundlers either warn, bundle a broad set of files, or leave the call to the browser. - Shared code is extracted. If two chunks both use the same library, many bundlers move it to a shared chunk so it downloads once.
Failure is part of the contract
The promise can reject. A network drop, a server error, or a deploy that deleted old chunk files will all cause a rejection. Plain code handles this with try and catch.
button.addEventListener('click', async () => {
try {
const { buildReport } = await import('./report.js');
console.log(buildReport([['id'], [1]]));
} catch (error) {
console.error('Could not load the report code', error);
}
});A later chapter shows how error boundaries handle the same failure inside React components.
Naming chunks
Bundlers let you label chunks for easier debugging. In webpack, a magic comment sets the name.
const module = await import(/* webpackChunkName: "report" */ './report.js');Vite uses Rollup and names chunks after the module by default, so no comment is needed. Names are a debugging aid. They do not change what loads.
Common errors
| Symptom | Likely cause |
|---|---|
| No separate chunk appears in the build | The same module is also imported statically elsewhere, so it stays in the main bundle |
| `module.default` is undefined | The module has only named exports |
| Chunk 404 after a deploy | The page references an old hashed filename that no longer exists on the server |
| Whole folder bundled into one chunk | The import path is built from a variable |
The first row is the most common. One static import anywhere in the app pulls the module back into the main bundle, so the dynamic import gains nothing.
Exercise
You add const { buildReport } = await import('./report.js') inside a click handler, but the build output shows no separate chunk for report.js. Another file contains import { buildReport } from './report.js'. What is happening, and how do you fix it?
Show answer
The static import in the other file forces the bundler to include report.js in the main bundle, so the dynamic import has nothing to split off. Change that file to use dynamic import too, or remove the static import. Then rebuild and confirm that a separate chunk file appears.
Exercise
What does import('./report.js') return, and what happens if the network request for the chunk fails?
Show answer
It returns a promise that resolves to the module namespace object. If the request fails, the promise rejects, so the caller must handle it with catch or try/catch.