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.default for 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 call import() 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)}`;
4
5const mod = await import(url); // the module namespace object
6console.log(mod.greet("Ada")); // Hello, Ada!
7console.log(mod.default("dynamic")); // DYNAMIC!
8
9// Same specifier -> same cached instance
10console.log((await import(url)) === mod); // true
11
12// 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 click
16 return createEditor();
17 } catch (err) {
18 console.log("could not load the editor:", err.message);
19 }
20}
21
22async function loadMessages(locale) {
23 const { default: messages } = await import(`./locales/${locale}.js`); // one chunk per locale
24 return messages;
25}
26
27console.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.

Open in study app