> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/module/es/import/dynamic-import.md).

# dynamic import()

{% tabs %}
{% tab title="📗 參考" %}

* V8.dev ⟩ [Dynamic import()](https://v8.dev/features/dynamic-import#dynamic) ⭐️
* JS.info ⟩&#x20;
  * [Dynamic imports](https://javascript.info/modules-dynamic-imports)
  * [Async/await](https://javascript.info/async-await)
    {% endtab %}

{% tab title="📘 手冊" %}

* MDN ⟩ [Dynamic Imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports)
  {% endtab %}
  {% endtabs %}

* import a module **on-demand**

* **compute** the **module specifier** at **runtime**

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

{% hint style="info" %}
**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.
{% endhint %}

{% hint style="danger" %}
**import** is **NOT** a **function**, it's **NOT** even an **object**.
{% endhint %}

{% tabs %}
{% tab title="index.mjs" %}

```javascript
/* 
  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');
        }
    };
}

```

{% endtab %}

{% tab title="books.mjs" %}

```javascript
// books.mjs
export const loadPageInto = (elem) => {
  elem.innerHTML = `I have no books`;
};
```

{% endtab %}

{% tab title="💾 程式" %}

* codeSandbox ⟩ [dynamic import](https://codesandbox.io/s/dynamic-import-mb9y5?file=/src/index.js)
  {% endtab %}
  {% endtabs %}
