JavaScriptMedium
What is Dynamic Import?
Dynamic import, import(specifier), loads an ES module at runtime and returns a promise of its module namespace object, so you can load code conditionally, on demand, or based on values only known at runtime.
Static vs dynamic import
- Static
import x from "./x.js"must be at the top level, with a fixed string, and is loaded before the module runs. import()can appear anywhere (inside functions, conditions, event handlers), can use computed paths, and loads the module only when called.
Uses
- Code splitting: bundlers create a separate chunk for each
import(), which is how route-based and component-based splitting work. - Load on interaction: open an editor, chart or emoji picker only when the user asks for it.
- Conditional features: polyfills only for browsers that need them, or a platform-specific implementation.
- Localisation:
await import(./locales/${lang}.js). - Loading ES modules from CommonJS code.
Details
- The result is the module namespace: use
mod.defaultfor the default export, or destructure named exports. - Modules are cached: importing the same specifier again returns the same instance without refetching.
- Errors (network failure, syntax error, missing file) reject the promise; handle them and show a fallback or retry.
- Bundlers need some static information to create chunks, so use template strings with a fixed directory rather than fully arbitrary variables.
- Preload chunks you will need soon (
<link rel="modulepreload">, or callimport()on hover).
Code example
js
1// Load a module on demand (in the playground we import from a data: URL so it runs anywhere)2const moduleSource = 'export const greet = (name) => "Hello, " + name + "!"; export default (text) => text.toUpperCase() + "!";';3const url = `data:text/javascript,${encodeURIComponent(moduleSource)}`;45const mod = await import(url); // the module namespace object6console.log(mod.greet("Ada")); // Hello, Ada!7console.log(mod.default("dynamic")); // DYNAMIC!89// Same specifier -> same cached instance10console.log((await import(url)) === mod); // true1112// Typical app patterns (bundlers turn each into a separate chunk):13async function openEditor() {14 try {15 const { createEditor } = await import("./editor.js"); // only downloaded on click16 return createEditor();17 } catch (err) {18 console.log("could not load the editor:", err.message);19 }20}2122async function loadMessages(locale) {23 const { default: messages } = await import(`./locales/${locale}.js`); // one chunk per locale24 return messages;25}2627console.log(typeof openEditor, typeof loadMessages);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.