Sub topic 2
Dynamic import() and chunks
This chapter explains what a dynamic import() is, how a bundler turns it into a separate file called a chunk, and what happens at runtime when the browser requests that chunk. It sits between the idea of code splitting and React.lazy, which builds on everything here.
Prerequisites
This chapter assumes you know the following:
- ES modules: static
importandexport, including default and named exports. - Promises:
.then,.catch, andasync/await. - What a bundler such as Vite or webpack does at a high level: it combines your source files into files the browser can load.
You do not need to know React internals. The examples in this chapter use plain JavaScript.
Static import versus dynamic import()
A static import declaration is part of the module's structure. It must appear at the top level 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 './formatDate.js';
console.log(formatDate(new Date()));A dynamic import() is an expression, not a declaration. You can call it anywhere: inside a function, inside an if, or inside an event handler. It takes a module specifier and returns a promise. The promise resolves to the module namespace object, which holds all the module's exports.
async function showReport() {
const module = await import('./report.js');
module.renderReport();
}
document.querySelector('#report-button').addEventListener('click', showReport);Until the user clicks the button, the browser does not download report.js. The code in that file is not part of the initial load.
The table summarizes the differences.
| Property | Static `import` | Dynamic `import()` |
|---|---|---|
| Syntax | Declaration at top level | Expression, usable anywhere |
| When it loads | Before the importing module runs | When the expression runs |
| Result | Bindings in scope | Promise of a module namespace object |
| Bundle effect | Same chunk as the importer | Separate chunk (usually) |
| Failure mode | Whole app fails to start | Promise rejects at the call site |
The last row matters for later chapters. A static import failure stops the app before it starts. A dynamic import failure happens while the app is running, so you can catch it and recover.
The module namespace object
The promise from import() resolves to an object with one property per export. A default export appears under the key default.
Suppose math.js contains this code:
export const PI = 3.14159;
export function square(x) {
return x * x;
}
export default function cube(x) {
return x * x * x;
}You can read each export from the resolved object:
async function demo() {
const math = await import('./math.js');
console.log(math.PI); // 3.14159
console.log(math.square(4)); // 16
console.log(math.default(3)); // 27
}
demo();You can also destructure and rename in one step:
async function demo() {
const { square, default: cube } = await import('./math.js');
console.log(square(4), cube(3));
}
demo();The default key is the reason React.lazy has a rule about default exports. React.lazy reads module.default from the resolved object. The next chapter returns to this.
What the bundler does with import()
When a bundler sees import('./report.js'), it treats report.js as a split point. It does three things:
- It builds a separate output file, called a chunk, that contains
report.jsand everything only it needs. - It replaces your
import()call with a call to its own loader function. The loader fetches the chunk file, runs it, and resolves the promise. - It keeps modules that several chunks share in a common chunk, so they are not duplicated in every file.
The result is a graph of chunks instead of one big file.
In the diagram, the dashed arrow is the dynamic edge. Everything reachable only through a solid arrow loads up front. The report chunk loads when the code reaches the import() call.
What counts as a shared module
If two dynamic imports both depend on the same library, the bundler does not copy that library into both chunks. It extracts a shared chunk. When the first chunk loads, the shared chunk loads with it. When the second chunk loads later, the browser reuses the shared chunk it already has.
If a module is also used by the main chunk, the bundler keeps it in the main chunk. The dynamic chunk then refers to it there.
Chunk file names
Production builds name chunks with a content hash, for example report-3f9a1c.js. The hash changes when the content changes. This allows long-lived caching: the browser can keep a chunk forever, and a new deploy produces a new file name when the content changes.
Vite and webpack both support this. Vite uses Rollup under the hood and names chunks by their source file by default. Webpack names them by numeric id unless you ask for something else.
Naming chunks
Names help when you read build output or network traces. Webpack supports a magic comment:
const module = await import(/* webpackChunkName: "report" */ './report.js');Vite and Rollup do not read that comment. In Vite you control naming through the build configuration instead:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rollupOptions: {
output: {
chunkFileNames: 'assets/[name]-[hash].js',
},
},
},
});The [name] placeholder takes the name from the source module, so report.js produces a chunk starting with report. Check your bundler's documentation for the options that apply to your version.
Seeing a split happen
A small experiment shows the behavior. Create these two files in a Vite project.
// src/heavy.js
export function work() {
return 'heavy module loaded';
}// src/main.js
const button = document.createElement('button');
button.textContent = 'Load heavy module';
document.body.append(button);
button.addEventListener('click', async () => {
const { work } = await import('./heavy.js');
console.log(work());
});Run the production build with npm run build. The output lists at least two JavaScript files in dist/assets: one for the entry and one for heavy.js. Serve the build with npm run preview, open the browser's Network panel, and reload. Only the entry file appears. Click the button, and the second file appears in the panel. The console prints heavy module loaded.
In the development server, Vite serves each module as a separate request already, so you will not see the same grouping. Test splitting against a production build.
Runtime behavior
Loading is asynchronous
The promise resolves only after the browser has downloaded and executed the chunk. Any code after await import(...) runs after that. Between the call and the resolution, the user is waiting. Later chapters cover how to show a loading indicator during this time. For now, remember that a dynamic import always costs at least one extra network round trip, unless the chunk is already loaded or cached.
Modules run once
The module system evaluates each module once and caches the result. Calling import('./report.js') a second time returns a promise for the same namespace object, and the module code does not run again.
const first = await import('./report.js');
const second = await import('./report.js');
console.log(first === second); // trueThis property is what makes preloading work. If you call import() early, a later call finds the module already loaded or already loading. The preloading chapter relies on it.
Parallel calls share one request
If two parts of the app call import('./report.js') at nearly the same time, the bundler's loader makes one network request. Both promises resolve when it finishes. You do not need to deduplicate calls yourself.
Failure
If the request fails, the promise rejects. Common causes are a lost connection, a server error, or a stale file name after a deploy.
async function openReport() {
try {
const { renderReport } = await import('./report.js');
renderReport();
} catch (error) {
console.error('Could not load the report module', error);
}
}Many browsers cache a failed dynamic import of the same URL for the lifetime of the page, so calling import() again may reject again without a new request. A page reload is the reliable recovery in that case. The error boundary chapter covers recovery strategies in React.
Common errors
The following mistakes come up often when learners first use dynamic imports.
- Forgetting the promise. Writing
const { work } = import('./heavy.js')withoutawaitor.thendestructures a promise, which givesundefined. Always await the result. - Expecting a split from a static import too. If any file in your app also imports
heavy.jsstatically, the bundler must keep it in the main chunk. The dynamic import still works, but nothing is split off. Search for static imports of the module you want to split. - Using a fully dynamic specifier.
import(path)with a runtime variable cannot be analyzed. Bundlers either warn, fail, or bundle a large set of files. Prefer a literal string. If you need variation, use a template literal with a clear prefix and extension, such as `import(./locales/${lang}.js)`. The bundler then creates one chunk for each matching file. - Testing in the dev server. As noted above, dev mode does not show the production chunk layout.
- Splitting too small. Each chunk costs a request. A module of a few hundred bytes is usually not worth its own chunk.
Which modules are good split points
A module is a good candidate when it is large, used by only part of your users, or needed only after an interaction. Typical examples:
- A charting or editor library used on one screen.
- A modal dialog that opens after a click.
- A locale file chosen at runtime.
- A feature behind a permission that most users lack.
A module is a poor candidate when it is needed for the first paint, because the user would wait for an extra request before seeing anything.
Summary
- Static imports join the importer's chunk. Dynamic
import()marks a split point. import()returns a promise of a namespace object. A default export is underdefault.- The bundler emits a chunk file, rewrites the call to use a loader, and extracts shared code into common chunks.
- Modules evaluate once. Repeated and parallel calls reuse the same result and request.
- A failed import rejects the promise at runtime, which you can catch.
Exercise
A teammate writes const { drawChart } = import('./chart.js'); inside a click handler, and drawChart is undefined when called. What is wrong, and how do you fix it? Then, after fixing it, the build output shows no separate chart chunk. Name one likely cause.
Show answer
import() returns a promise, so destructuring it directly reads properties from the promise object, which has no drawChart. Make the handler async and write const { drawChart } = await import('./chart.js');, or use .then. If no chart chunk appears, a likely cause is that another file imports chart.js with a static import, which forces the bundler to keep it in the main chunk. Remove or convert that static import.
Exercise
A module locale.js is imported with await import('./locale.js') twice, once at startup and once when the user opens Settings. How many times does the module's top-level code run, and how many network requests does the second call make if the first has finished?
Show answer
The top-level code runs once, because the module system caches evaluated modules. The second call makes no new network request, since the module is already loaded. Both calls resolve to the same namespace object.