Dynamic Imports and Import Maps
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 canrequireES modules.
import()
Syntax
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
export function buildReport(payments) {
const total = payments.reduce((a, b) => a + b, 0);
return `Report: ${payments.length} payments, $${total}`;
}
export default "report module v1"; 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);App started; report code not loaded yet
report module v1
Report: 3 payments, $250
second import is the same module: functionExplanation: 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:
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;
}
});<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>page ready, module not loaded
loading module on demand...
Grade 9: $165, Grade 12: $300Conditional and Computed Loading
const { formatter } = navigator.language.startsWith("es")
? await import("./locale/es.js")
: await import("./locale/en.js");
const plugin = await import(`./plugins/${pluginName}.js`); // computed pathImport 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:
<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.
<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>$120.50JSON 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:
{ "9": 400, "10": 415, "11": 430, "12": 445 }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:
const CURRENCY = "USD";
function formatCents(cents) {
return `$${(cents / 100).toFixed(2)}`;
}
module.exports = { CURRENCY, formatCents }; const { formatCents, CURRENCY } = require("./money.cjs");
console.log(formatCents(12050), CURRENCY, typeof require, typeof module);$120.50 USD function object| ES modules | CommonJS | |
|---|---|---|
| Syntax | import / export | require() / module.exports |
| Loading | Static (analyzed before running), asynchronous | Dynamic, synchronous |
| Browsers | Native | No (needs a bundler) |
Top-level await | Yes | No |
| Imports | Live, read-only bindings | Copies 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, __filename | import.meta.dirname, import.meta.filename | Available |
Mixing the Two
- An ES module can import CommonJS:
import pkg from "./old.cjs"givesmodule.exportsas 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 allowsrequire("./new.mjs")for ES modules without top-levelawait.
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:
export function exportPdf(rows) {
return `PDF with ${rows.length} rows (${rows.map((r) => r.name).join(", ")})`;
} 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" }]));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
export const format = (n) => n.toLocaleString("en-US", { style: "currency", currency: "USD" }); Show solution
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));$1,234.50Looking 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.
Key Takeaways
| Task | Code |
|---|---|
| Load on demand | const { f } = await import("./f.js") |
| Default export | (await import("./x.js")).default |
| Bare names in browsers | <script type="importmap"> |
| Import JSON | import data from "./d.json" with { type: "json" } |
| CommonJS | const x = require("./x.cjs"); module.exports = ... |
Was this tutorial helpful?