dynamic import()

  • import a module on-demand

  • compute the module specifier at runtime

  • import a module from within a regular script (non-module)

import(specifier) returns a promise for the module namespace object of the requested module, which is created after fetching, instantiating, and evaluating all of the module’s dependencies, as well as the module itself.

import is NOT a function, it's NOT even an object.

/* 
  https://v8.dev/features/dynamic-import#dynamic

  ⭐️ static import use cases 
  --------------------------
  • static analysis
  • bundling tools 
  • tree-shaking

  ⭐️ dynamic import
  -----------------
  • import a module on-demand
  • compute the module specifier at runtime
  • import a module from within a regular script (non-module)
*/

// static import
import { $, $all } from './helpers.mjs';
import * as module from './utils.mjs';

module.default();
// 'Hi from the default export!'

module.doStuff();
// Doing stuff…

// --------------- dynamic import ---------------

// ⭐️ import on-demand
(async () => {
    /* 
      🔸 Note:
         import() looks like a function call,
         but it's NOT a function, it's even NOT an object❗️
     */
    const module = await import('./utils.mjs');

    module.default();
    // 'Hi from the default export!'
    module.doStuff();
    // 'Doing stuff…'
})();

const main = $('main');
const links = $all('nav > a');

// add 'onclick' to every link in <nav.
for (const link of links) {
    // ⭐️ async event handler
    link.onclick = async (e) => {
        // prevent url redirect
        e.preventDefault();

        const modulePath = `./${link.dataset.entryModule}.mjs`;
        main.classList.remove('placeholder');

        try {
            // ⭐️ dynamic import
            const module = await import(modulePath);

            // ⭐️ assumn: module exports a function named `loadPageInto`
            module.loadPageInto(main);

            main.classList.add('content');
            main.classList.remove('error');
        } catch (error) {
            main.textContent = error.message;
            main.classList.add('error');
            main.classList.remove('content');
        }
    };
}

Last updated