Sub topic 9
How Bundlers Split Code at import()
This chapter assumes you already know the import() expression, module namespace objects, and how computed specifiers resolve. Those topics come from earlier chapters. You should also have built a project with a bundler such as Vite, Rollup, esbuild, or webpack at least once. The examples use Vite and webpack because their behavior is well documented and they are common in real projects.
In plain ES modules, import() makes the browser fetch one file at runtime. A bundler changes this. It sees every import() call while it builds the module graph, and it treats each call as a place where the graph can be cut. The code behind that cut goes into a separate output file called a chunk. At runtime, the chunk is fetched only when the import() call runs.
The Working Model: Entry Chunks and Async Chunks
A bundler starts at your entry file and follows every static import declaration. All modules reached this way go into the entry chunk, the file your HTML loads first. When the bundler reaches an import('./chart.js') call, it does not add chart.js to the entry chunk. It starts a new async chunk rooted at chart.js and adds every module that chart.js statically imports.
The rules behind this picture:
- A static edge keeps modules together. If
Astatically importsB, thenBmust be available whenAruns, so both go into the same chunk or into chunks that load together. - A dynamic edge is a split point. Code behind
import()can be deferred because the caller already expects a promise. - Shared modules are extracted. If two async chunks both need
format.js, the bundler puts it in a shared chunk so it is not downloaded twice. - Filenames are content-hashed. A name like
chart-c3d4.jschanges whenever the content changes, so browsers can cache chunks for a long time.
What the Bundler Writes in Place of import()
Take this source file:
// main.js
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});Vite and Rollup produce ES module output, so the built code still calls native import(). The specifier is rewritten to the hashed chunk path. Vite also wraps the call in a small helper that preloads the chunk's own dependencies, roughly like this:
// Simplified shape of Vite output (not meant to be run on its own)
button.addEventListener('click', async () => {
const { renderChart } = await __vitePreload(
() => import('./chart-c3d4.js'),
['assets/format-9a8b.js']
);
renderChart(document.querySelector('#chart'));
});webpack uses its own module runtime by default. The call becomes something like __webpack_require__.e(id).then(...). That function adds a <script> tag for the chunk, waits for it to register its modules, and then resolves with the namespace object. In both cases your code sees the same thing: a promise for the module namespace.
How Specifier Shape Affects Splitting
The bundler can only split what it can analyze while building. The shape of the specifier decides what it is able to do.
| Specifier form | Example | What the bundler does |
|---|---|---|
| String literal | `import('./chart.js')` | One async chunk for that module |
| Template literal with a static prefix | ``import(`./locales/${lang}.js`)`` | Matches every file under `./locales/` that fits the pattern and makes one chunk per file |
| Fully dynamic expression | `import(url)` | Cannot analyze it. The call is left as a runtime import, and the bundler usually warns |
| Bare package name | `import('sharp')` | Resolves the package and splits it like a literal |
The template-literal case is useful, and it can surprise people. webpack calls the result a context module. Vite uses glob matching for it. If the ./locales/ folder holds 40 files, you get 40 chunks, plus a lookup map that converts lang into the right chunk path. Keep such folders limited to files you really mean to load. A stray ./locales/test-fixtures.js will be built and shipped as well.
For a fully dynamic specifier, webpack reports "Critical dependency: the request of a dependency is an expression." Vite asks you to add /* @vite-ignore */ if you meant to leave the import unbundled. A runtime import like that has to point to a URL that actually exists on the server, because the bundler never processed the file.
Controlling Chunks
Most projects work fine with the default splitting. You only need to step in when you have a specific reason, such as readable chunk names, grouping vendor code, or prefetching.
webpack reads magic comments placed inside the import() call:
const { renderChart } = await import(
/* webpackChunkName: "chart" */
/* webpackPrefetch: true */
'./chart.js'
);webpackPrefetch adds <link rel="prefetch"> after the parent chunk loads. The browser then downloads the chunk during idle time, so the click feels instant.
In Vite, you group modules through Rollup's manualChunks option:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules/chart.js')) {
return 'vendor-chart';
}
},
},
},
},
});Common Errors
A static import cancels the split
If any module reached from the entry chunk statically imports chart.js, then chart.js has to be in the entry chunk. The import() call elsewhere still works, but it resolves right away with a module that is already loaded. You save nothing. Vite warns about this: "is dynamically imported by ... but also statically imported by ..., dynamic import will not move module into another chunk." Search for every import of the module and convert all of them, or accept that the module loads up front.
The same thing happens with barrel files. If index.js re-exports chart.js and the entry chunk imports anything from index.js, then chart.js lands in the entry chunk. Tree-shaking can sometimes remove unused re-exports, but side effects in the module can prevent that.
Chunks 404 after a deploy
A user opens the app, and then you deploy. The old entry chunk still refers to chart-c3d4.js, but the server now has only chart-77ef.js. The next click fails. webpack throws a ChunkLoadError. With native import() you get a TypeError such as "Failed to fetch dynamically imported module." Two fixes help: keep old assets on the server for a while after each deploy, and recover in the client:
async function importWithReload(loader) {
try {
return await loader();
} catch (err) {
const key = 'chunk-reload-attempted';
if (!sessionStorage.getItem(key)) {
sessionStorage.setItem(key, '1');
window.location.reload();
return new Promise(() => {}); // page is reloading
}
throw err;
}
}
const { renderChart } = await importWithReload(() => import('./chart.js'));
sessionStorage.removeItem('chunk-reload-attempted');Pass a function rather than a specifier string. That keeps the literal import('./chart.js') visible to the bundler so it can still split the chunk. If you wrote import(spec) inside the helper, splitting would stop.
Wrong public path
Chunks are fetched relative to a configured base URL: base in Vite, output.publicPath in webpack. If the app is served from /app/ and the base is /, the entry chunk loads but every async chunk returns 404. This often shows up only in production.
Over-splitting
Each chunk costs a request plus some runtime overhead. Splitting off a 2 KB module that every page needs makes the app slower. Split at route boundaries and at large, rarely used features such as editors, charts, PDF export, and admin panels.
Deciding Where to Split
| Situation | Split with import()? |
|---|---|
| Route or page the user may never visit | Yes |
| Large library behind a button or a dialog | Yes, and consider prefetch |
| Locale or theme files where only one is used | Yes, with a template literal |
| Small utility used on startup | No |
| Module already imported statically elsewhere | Not unless you remove the static import too |
| Code needed within the first render | No. A split here only adds a waterfall |
Exercise
Your entry file has button.onclick = () => import('./editor.js'), but the build output shows editor.js inside the main chunk, and there is no editor chunk. What is the most likely cause, and how do you confirm it?
Show answer
Some module reached from the entry chunk imports editor.js statically, either directly or through a barrel file that re-exports it. That forces editor.js into the main chunk. To confirm, read the bundler warning (Vite reports modules that are "dynamically imported ... but also statically imported"), or search the project for imports of editor.js and its re-exports. Then use a bundle analyzer to see which module pulls it in.
Exercise
A locales/ folder holds en.js, fr.js, de.js, and a large helpers.js that only the build scripts use. The app calls import(./locales/${lang}.js). What does the bundler produce, and what is the problem?
Show answer
The bundler matches every .js file in locales/ and creates a chunk for each one: en, fr, de, and helpers. It also creates a lookup map from the computed path to the chunk. The helpers.js file gets built and shipped, and a crafted lang value can load it. Move helpers.js out of the folder, or narrow the pattern, for example `import(./locales/${lang}.locale.js)`.
Exercise
Why does the importWithReload helper take a function () => import('./chart.js') and not a string such as './chart.js'?
Show answer
The bundler can only split at an import() call with a specifier it can analyze. With a function, the literal import('./chart.js') stays in the source, so the bundler still makes and maps the chunk. If the helper called import(spec) with a variable, the specifier would be fully dynamic. The bundler could not split it, and at runtime it would request an unbundled path that probably does not exist.