Dynamic import and loading failures
How it works
import(specifier) is an expression returning a promise for the module namespace. It allows a module request to occur when needed rather than at static linking time. Handle rejection: resolution, loading, parsing or evaluation can fail. A resolved namespace is not the default value itself; use its default property when appropriate. Do not concatenate untrusted paths into unrestricted dynamic imports.
Example 1
Save each file separately. Run with Node.js: main.mjs. This is a multi-file example, not a single editor snippet.
feature.mjs
main.mjs
try { const ns = await import("./feature.mjs"); console.log(ns.default); await import("./absent.mjs");} catch { console.log("load failed"); }Expected output in the tested environment:
readyload failedThe valid import yields a namespace; a missing local module rejects and is caught.
Common mistake
import() is not a synchronous require replacement. Returning its promise without awaiting or chaining it can leave failures unhandled.
Practice
Use a fixed allowlist of two module names and reject all other choices before requesting a module.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dynamic import and loading failures — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
What does a successful dynamic import fulfill with?
Which failure can reject import()?
Why use a fixed mapping for user-selected module names?
Can import() be called inside a conditional branch?
For Dynamic import and loading failures, what is the console output of example 1 in Node.js 22.16.0?
// File: feature.mjsexport default "ready";
// File: main.mjstry { const ns = await import("./feature.mjs"); console.log(ns.default); await import("./absent.mjs");} catch { console.log("load failed"); }