JS: Module. Dynamic Import

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2020)

What is Dynamic Import

Dynamic import is introduced in ECMAScript 2020. It let you import a module at run-time. You can import a module by condition inside a if-statement, and module name can also be a variable.

Import and export of ECMAScript 2015 are static. That means, the code runs at compile time. You cannot import at run time, such as import a lib only when needed.

Dynamic Import Syntax

import(moduleSpecifier)

xtodo
work in progress

read

import(moduleSpecifier).then((x_module) => {
 // x_module is a object. keys are exported names.
 const { default: MyComponent } = x_module;
});

Full Example

// file name: lib.js
const f1 = ((x) => (x + 1));
const f2 = ((x) => (x + 2));
export { f1, f2 };
// Static import (for comparison) - must be at top level
// import { greet } from './utils.js'; // This would fail if conditional

async function loadAndUseUtils() {
  try {
    // Dynamic import with a variable path (e.g., based on condition)
    const modulePath = './utils.js'; // Could be dynamic: `./modules/${feature}.js`

    const utils = await import(modulePath); // Await the Promise

    // Access named export
    console.log(utils.greet('World')); // "Hello, World!"

    // Access default export
    const FancyGreet = utils.default;
    console.log(FancyGreet('Grok')); // "🌟 Hello, Grok! 🌟"
  } catch (error) {
    console.error('Failed to load module:', error);
  }
}

// Trigger on button click (lazy loading example)
document.getElementById('load-btn').addEventListener('click', loadAndUseUtils);

In ECMAScript 2022 , you can use await at the top level in modules (not scripts), making dynamic imports cleaner.

const utils = await import('./utils.js');
console.log(utils.greet('Top-level!'));

JavaScript. Module Import Export