Dynamic Imports and Import Maps

Updated · 8 min read
hardES2026javascriptmodulesdynamic-importimport-mapscommonjs

Static import statements load every dependency before a module runs. Often that's wasteful: the chart library is only needed when someone opens the reports page, and the PDF exporter only when someone clicks Export. Dynamic import, written import(specifier), loads a module on demand and returns a promise of it. This lesson also covers import maps (letting browsers resolve bare names like "date-fns"), JSON modules through import attributes, and CommonJS, the older Node.js module system you'll meet in existing code.

In One Minute

  • const mod = await import("./charts.js") loads a module at run time; the promise resolves to its namespace object.
  • Use it for lazy loading (features used rarely), conditional loading, and loading from computed paths.
  • Import maps (<script type="importmap">) map bare specifiers to URLs in the browser.
  • JSON modules: import config from "./config.json" with { type: "json" } (ES2025).
  • CommonJS (require, module.exports) is Node.js's older system; ES modules can import it, and modern Node.js can require ES modules.

import()

Syntax

syntax.js
const module = await import(specifier);   // specifier can be any string expression
const { named, default: Default } = await import("./file.js");

import() looks like a function call but is special syntax. It works in both modules and classic scripts, and its argument can be computed at run time.

Example

report.js▶ Try it
export function buildReport(payments) {
  const total = payments.reduce((a, b) => a + b, 0);
  return `Report: ${payments.length} payments, $${total}`;
}
export default "report module v1";
Output
 
lazy.js▶ Try it
console.log("App started; report code not loaded yet");
 
async function onReportClick(payments) {
  const { buildReport, default: version } = await import("./report.mjs");
  console.log(version);
  return buildReport(payments);
}
 
console.log(await onReportClick([120, 85, 45]));
const again = await import("./report.mjs");
console.log("second import is the same module:", typeof again.buildReport);
Output
App started; report code not loaded yet
report module v1
Report: 3 payments, $250
second import is the same module: function

Explanation: the report module is loaded only when onReportClick runs. The promise resolves to the module's namespace object, from which you destructure named exports, and default for the default export. Importing the same module again returns the same, already-loaded instance: modules run once.

Lazy Loading in the Browser

Lazy loading keeps the first page load small and fast: large or rarely used code is downloaded only when needed. Bundlers (next lessons) automatically split each import() target into a separate file:

lazy-chart.js
document.querySelector("#show-chart").addEventListener("click", async (event) => {
  event.currentTarget.disabled = true;
  try {
    const { renderChart } = await import("./chart.js");   // downloaded on first click only
    renderChart(document.querySelector("#chart"), totalsByGrade);
  } catch (err) {
    showMessage("The chart couldn't load. Check your connection and try again.");
  } finally {
    event.currentTarget.disabled = false;
  }
});
dynamic-page.html
<button id="show">Show totals</button>
<p id="out"></p>
<script type="module">
  const chartModuleUrl = "data:text/javascript," + encodeURIComponent(
    "export const render = (data) => data.map(([g, t]) => `Grade ${g}: $${t}`).join(', ');"
  );
  document.querySelector("#show").addEventListener("click", async () => {
    console.log("loading module on demand...");
    const { render } = await import(chartModuleUrl);
    document.querySelector("#out").textContent = render([[9, 165], [12, 300]]);
    console.log(document.querySelector("#out").textContent);
  });
  console.log("page ready, module not loaded");
</script>
Output
page ready, module not loaded
loading module on demand...
Grade 9: $165, Grade 12: $300

Conditional and Computed Loading

conditional.js
const { formatter } = navigator.language.startsWith("es")
  ? await import("./locale/es.js")
  : await import("./locale/en.js");
 
const plugin = await import(`./plugins/${pluginName}.js`);   // computed path

Import Maps

Node.js resolves bare specifiers like import { format } from "date-fns" by looking in node_modules. Browsers don't know what "date-fns" means. An import map tells them:

import-map.html
<script type="importmap">
{
  "imports": {
    "date-fns": "https://cdn.jsdelivr.net/npm/date-fns@4.1.0/+esm",
    "@fee-tracker/": "/js/"
  }
}
</script>
<script type="module">
  import { format } from "date-fns";
  import { formatCents } from "@fee-tracker/money.js";   // resolves to /js/money.js
</script>

The import map must come before any module that uses it. Entries can map a whole package name or a prefix (ending in /). Import maps let small sites use packages without a bundler; larger apps usually let the bundler handle resolution.

importmap-check.html
<script type="importmap">
{ "imports": { "money": "data:text/javascript,export const usd = (n) => '$' + n.toFixed(2);" } }
</script>
<script type="module">
  import { usd } from "money";
  console.log(usd(120.5));
</script>
Output
$120.50

JSON Modules and Import Attributes

Import attributes (ES2025) add information to an import with the with keyword. Their first use is JSON modules: importing a JSON file as data, safely:

fees.json
{ "9": 400, "10": 415, "11": 430, "12": 445 }
json-import.js
import fees from "./fees.json" with { type: "json" };
console.log(fees["11"]);   // 430
 
const settings = await import("./settings.json", { with: { type: "json" } });
console.log(settings.default.currency);

The type: "json" attribute is required for security: it guarantees the file is treated as data and can never run as code, even if a server sends JavaScript. JSON modules have only a default export. They run in Node.js 26 and current browsers (checked November 2026).

CommonJS: The Older Node.js Way

Before ES modules, Node.js used CommonJS. You'll find it in many existing projects, npm packages and tutorials:

money.cjs▶ Try it
const CURRENCY = "USD";
function formatCents(cents) {
  return `$${(cents / 100).toFixed(2)}`;
}
module.exports = { CURRENCY, formatCents };
Output
 
app.cjs▶ Try it
const { formatCents, CURRENCY } = require("./money.cjs");
console.log(formatCents(12050), CURRENCY, typeof require, typeof module);
Output
$120.50 USD function object
ES modulesCommonJS
Syntaximport / exportrequire() / module.exports
LoadingStatic (analyzed before running), asynchronousDynamic, synchronous
BrowsersNativeNo (needs a bundler)
Top-level awaitYesNo
ImportsLive, read-only bindingsCopies of module.exports at the time of require
File extensions in Node.js.mjs, or .js with "type": "module".cjs, or .js without it
__dirname, __filenameimport.meta.dirname, import.meta.filenameAvailable

Mixing the Two

  • An ES module can import CommonJS: import pkg from "./old.cjs" gives module.exports as the default export (Node.js also detects many named exports).
  • CommonJS can load ES modules with await import("./new.mjs") anywhere, and modern Node.js (22.12 and later, including Node.js 26) also allows require("./new.mjs") for ES modules without top-level await.

In Practice

The Fee Tracker loads its PDF export code only when the user asks for it, shows progress, and caches the loaded module so a second export is instant:

pdf-export.js▶ Try it
export function exportPdf(rows) {
  return `PDF with ${rows.length} rows (${rows.map((r) => r.name).join(", ")})`;
}
Output
 
exporter.js▶ Try it
let pdfModule;
 
async function exportReport(rows) {
  if (!pdfModule) {
    console.log("Preparing export (loading the PDF tools)...");
    pdfModule = await import("./pdf-export.mjs");
  }
  return pdfModule.exportPdf(rows);
}
 
console.log(await exportReport([{ name: "Navika" }, { name: "Advitha" }]));
console.log(await exportReport([{ name: "Srihitha" }]));
Output
Preparing export (loading the PDF tools)...
PDF with 2 rows (Navika, Advitha)
PDF with 1 rows (Srihitha)

Common Mistakes

Forgetting that import() returns a promise. import("./x.js").render() fails. await it first.

Reading a default export directly from the namespace. Use (await import(path)).default or destructure { default: X }.

Importing JSON without with { type: "json" }. It fails. Add the attribute.

Mixing require and import in the same file. A file is either CommonJS or an ES module.

Practice

Challenge: Write loadFormatter(locale) that dynamically imports the formatter module for a locale (falling back to US English) and returns its format function, then use it.

Show solution
fmt-en.js▶ Try it
export const format = (n) => n.toLocaleString("en-US", { style: "currency", currency: "USD" });
Output
 
Show solution
fmt-loader.js▶ Try it
const FORMATTERS = { "en-US": "./fmt-en.mjs" };
 
async function loadFormatter(locale) {
  const { format } = await import(FORMATTERS[locale] ?? FORMATTERS["en-US"]);
  return format;
}
 
const format = await loadFormatter("en-US");
console.log(format(1234.5));
Output
$1,234.50

Looking the path up in a fixed table, rather than building it from the locale string, means only known files can ever be loaded. A real app would list one module per supported locale.

Quick check: Dynamic imports

3 questions
1What does import("./charts.js") return?
2What are import maps for?
3How is a JSON file imported as a module?

Key Takeaways

TaskCode
Load on demandconst { f } = await import("./f.js")
Default export(await import("./x.js")).default
Bare names in browsers<script type="importmap">
Import JSONimport data from "./d.json" with { type: "json" }
CommonJSconst x = require("./x.cjs"); module.exports = ...

Was this tutorial helpful?

Lesson 112 of 139