Sub topic 6
When a Dynamic Import Fails
This chapter assumes you know how import() returns a promise for a module namespace object, and that you are comfortable with async/await and try/catch. A dynamic import can fail like any other network or runtime operation. This chapter covers the ways it fails and how to recover.
Why an import() Promise Rejects
The promise returned by import() rejects whenever any step of loading the module fails. The error you catch depends on which step went wrong.
| Stage | Typical cause | Typical error |
|---|---|---|
| Resolve | Bare specifier with no import map, or an unknown package | `TypeError`, or `ERR_MODULE_NOT_FOUND` in Node.js |
| Fetch | File missing, server down, user offline | `TypeError: Failed to fetch dynamically imported module` |
| Parse and link | Syntax error, or a static `import { x }` of an export that does not exist | `SyntaxError` |
| Evaluate | Top-level code in the module, or in one of its dependencies, throws | Whatever was thrown |
A failure in any dependency of the target module rejects the whole import. The module and its static imports load as a single unit.
Catching Failures with a Fallback
Since import() returns a promise, an await inside try/catch handles every row of the table above. A common pattern is to fall back to a module you know exists:
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;
}
}If you are not using async functions, you can attach .catch() instead:
import('./analytics.js')
.then((mod) => mod.init())
.catch((err) => console.warn('Analytics unavailable', err));Common Mistakes
- Forgetting to await or catch. A dynamic import with no handler that fails produces an unhandled rejection. In a click handler, the user just sees nothing happen.
- Treating every error as "not found." A
SyntaxErroror a thrown evaluation error points to a bug, not a missing file. Log the actual error before you fall back, so these bugs don't stay hidden. - Expecting a retry to work. Runtimes cache module records by URL. If a module throws during evaluation, every later
import()of that URL rejects with the same error. Browsers also generally remember a failed fetch for the lifetime of the page. To retry after a network failure, change the URL, for example `import(./chart.js?retry=${Date.now()})`. Be aware that this gives you a separate module instance. - Hiding the problem from the user. A rejected import is often the first sign of a stale deployment, where old HTML asks for chunk files that are no longer on the server. In that case, showing a "reload the page" message usually helps more than a silent fallback.
Exercise
A module widget.js throws an error during evaluation because a global it expects is missing. Your code catches the rejection, defines the global, and calls import('./widget.js') again. What happens, and why?
Show answer
The second import rejects with the same error. The runtime caches the module record for that URL together with its evaluation error, so the module is not evaluated again. To get a fresh evaluation, you must import a different URL, for example by adding a query string, or reload the page.
Exercise
In loadMessages, what happens if both ./locales/fr.js and ./locales/en.js fail to load?
Show answer
The first rejection is caught and logged. Then await import('./locales/en.js') rejects inside the catch block, so loadMessages itself returns a rejected promise. The caller must handle that error, or the function needs a final fallback such as an inline default object.