Sub topic 6
When a Dynamic Import Fails
A static import that fails stops the whole module graph before any of your code runs. An import() call fails differently. It returns a promise, and that promise rejects. Your code keeps running, and you decide what happens next. This chapter covers where those failures come from, how to catch them, how to fall back or retry safely, and which failures the runtime remembers.
This chapter assumes you know async/await and promise rejection, and that you have read the earlier chapters on the import() expression and module namespace objects.
Where import() Can Fail
An import() call goes through several stages before its promise fulfills. A failure at any stage rejects the promise.
| Stage | Typical cause | What you usually see |
|---|---|---|
| Resolve | Bare specifier with no import map in the browser, or a package that is not installed in Node | `TypeError` in browsers; `ERR_MODULE_NOT_FOUND` in Node |
| Fetch | 404, offline, CORS, wrong MIME type, a stale chunk after a deploy | `TypeError: Failed to fetch dynamically imported module` (the message differs by browser) |
| Parse | Syntax error in the target or in any module it imports | `SyntaxError` |
| Link | A module in the loaded graph statically imports a name that does not exist | `SyntaxError: ... does not provide an export named ...` |
| Evaluate | Top-level code in the module, or in one of its dependencies, throws | Whatever was thrown |
The rejection covers the whole subgraph. If chart.js statically imports axis.js, and axis.js has a syntax error, then import('./chart.js') rejects even though chart.js itself is fine.
Catching the Rejection
Because import() returns a promise, you handle failures the same way you handle any other async failure. You can use try/catch around await, or .catch() on the promise.
async function loadMessages(lang) {
try {
const mod = await import(`./locales/${lang}.js`);
return mod.default;
} catch (err) {
console.warn(`Locale "${lang}" failed to load, using English`, err);
const fallback = await import('./locales/en.js');
return fallback.default;
}
}The same logic in promise-chain form:
function loadMessages(lang) {
return import(`./locales/${lang}.js`)
.then((mod) => mod.default)
.catch((err) => {
console.warn(`Locale "${lang}" failed to load, using English`, err);
return import('./locales/en.js').then((mod) => mod.default);
});
}Notice that the fallback import is not protected. If en.js is also missing, loadMessages rejects. That is usually the right behavior, because your guaranteed fallback being broken is a real bug and should be loud.
Do Not Swallow Every Error
A blanket catch that always falls back hides real bugs. If fr.js has a syntax error, the code above quietly shows English, and nobody notices that the French build is broken. Decide which failures count as "this module is legitimately unavailable" and rethrow the rest.
In Node.js, a missing file or package has a stable error code:
// main.mjs
async function loadPlugin(name) {
try {
return await import(`./plugins/${name}.mjs`);
} catch (err) {
if (err.code === 'ERR_MODULE_NOT_FOUND') {
console.warn(`Plugin "${name}" not found; skipping`);
return null;
}
throw err; // syntax errors, evaluation errors: surface them
}
}
const plugin = await loadPlugin('markdown');
if (plugin) plugin.default();Browsers do not give you a reliable code. Network, 404, and MIME-type failures all show up as a TypeError, and the message text differs between engines. A practical rule for the browser is to treat TypeError as "could not fetch" and to rethrow SyntaxError and anything else.
async function loadOptionalWidget() {
try {
return await import('./widget.js');
} catch (err) {
if (err instanceof TypeError) return null; // fetch-level failure
throw err;
}
}This rule is a heuristic. A TypeError thrown by the widget's own top-level code would also match it. If that matters to you, make the module's top-level code do nothing beyond defining exports, so that real work happens in functions you call after loading.
The Silent Failure: Missing Named Exports
One mistake does not reject at all. With a static import, a misspelled name is a link-time SyntaxError. With import(), you get back a namespace object, and reading a property that does not exist on an object just gives undefined.
// Static: fails before any code runs
// import { renderChrat } from './chart.js'; // SyntaxError
// Dynamic: the import succeeds, the destructured value is undefined
const { renderChrat } = await import('./chart.js');
renderChrat(); // TypeError: renderChrat is not a functionThe error shows up later and further from its cause. When a module's shape comes from outside your control, as with plugins, check it explicitly:
const mod = await import('./plugins/markdown.mjs');
if (typeof mod.activate !== 'function') {
throw new Error('Plugin "markdown" does not export an activate() function');
}
mod.activate();Which Failures Are Remembered
The runtime caches modules by their resolved URL. That cache also holds on to some failures, and this changes whether a retry can work.
Evaluation errors are cached permanently. Once a module throws during evaluation, the module record stays in an errored state. Every later import of the same URL rejects with the same error object, and the code is not run again.
// flaky.mjs
throw new Error('boom during evaluation');// main.mjs
let first;
for (let i = 0; i < 2; i++) {
try {
await import('./flaky.mjs');
} catch (err) {
first ??= err;
console.log(i, err.message, err === first);
}
}
// 0 boom during evaluation true
// 1 boom during evaluation trueParse and link errors behave the same way, since the source has not changed. Fetch failures differ between environments. Some browsers remember a failed fetch for the life of the page, and others try again. Do not count on a plain retry of the same URL working in every browser.
Retrying Network Failures
For flaky networks, a retry with backoff can recover. To get past any cached fetch failure, later attempts use a different URL by adding a query string. The query string makes it a new key in the module map.
// import-retry.js
export async function importWithRetry(url, attempts = 3) {
for (let i = 0; i < attempts; i++) {
const specifier = i === 0 ? url : `${url}?retry=${i}`;
try {
return await import(specifier);
} catch (err) {
const isFetchError = err instanceof TypeError;
if (!isFetchError || i === attempts - 1) throw err;
await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** i));
}
}
}// app.js
import { importWithRetry } from './import-retry.js';
const url = new URL('./chart.js', import.meta.url).href;
const { renderChart } = await importWithRetry(url);
renderChart(document.querySelector('#chart'));This helper has three gotchas you should know about:
- The caller passes an absolute URL. A relative specifier inside
import()resolves against the file that contains the call. Here that file isimport-retry.js, notapp.js. Building the URL withimport.meta.urlin the caller avoids loading the wrong path. chart.js?retry=1is a separate module instance fromchart.js. If another part of the app later importschart.jsdirectly, it gets a second copy with its own state. Keep this pattern for leaf modules that hold no shared state.- Query strings only help with unbundled URLs. Bundler chunk names are generated at build time, and the next chapters cover how bundlers handle the
import()calls they rewrite.
Stale Chunks After a Deploy
A common production failure looks like this. A user loads your app, you deploy a new build, and the old hashed chunk files are deleted from the server. When the user clicks something that triggers import('./settings.js'), the old chunk URL returns 404. Retrying does not help, because the file is gone.
The usual fix is to treat that failure as "the app is out of date" and reload the page. Vite fires a vite:preloadError event on window for this case. Without a bundler hook, you can handle it at the call site:
async function openSettings() {
try {
const { showSettings } = await import('./settings.js');
showSettings();
} catch (err) {
if (err instanceof TypeError && !sessionStorage.getItem('reloaded')) {
sessionStorage.setItem('reloaded', '1');
location.reload();
return;
}
throw err;
}
}The sessionStorage flag stops an endless reload loop if the chunk is missing for some other reason.
Choosing a Strategy
| Situation | Strategy |
|---|---|
| Optional feature or plugin | Catch "not found", return `null`, rethrow everything else |
| Content with a safe default (locales, themes) | Fall back to a known-good module and let the fallback fail loudly |
| Unreliable network | Retry fetch-stage errors with backoff and a fresh URL |
| Chunk missing after a deploy | Reload the page once |
| Error thrown during evaluation | Do not retry; report it and fix the module |
Exercise
A page calls import('./report.js'). The first call rejects because report.js threw new Error('DB not ready') from its top-level code. Five seconds later the database is ready and the page calls import('./report.js') again. What happens, and why?
Show answer
The second call rejects with the same Error('DB not ready') object, and the module's code does not run again. The module map caches modules by resolved URL. A module that failed during evaluation stays in an errored state, so later imports of that URL reuse the stored error. The fix is to move the database work out of top-level code and into an exported function the caller can retry.
Exercise
Why does const { tabel } = await import('./table.js') not reject when table.js only exports table, and how would you catch the mistake early?
Show answer
import() resolves to a namespace object, and destructuring a missing property from an object gives undefined instead of throwing. Only static imports check names at link time. To catch it early, check the namespace after loading, for example if (typeof mod.tabel !== 'function') throw new Error(...), or use a static import when the module is always needed.
Exercise
In a Node.js plugin loader, the catch block falls back to a default plugin on any error. A plugin file with a typo in its syntax now silently gets replaced by the default. Rewrite the condition so that only missing plugins fall back.
Show answer
Check the error code and rethrow everything else: catch (err) { if (err.code === 'ERR_MODULE_NOT_FOUND') return import('./plugins/default.mjs'); throw err; }. A syntax error is a SyntaxError with no such code, so it propagates to the caller.