Dynamic import
import() is a function that returns a promise, which makes loading a module something you can decide at runtime.
Unlike the static form, import() can appear anywhere, take a computed path, and be awaited. It resolves to the module namespace object, so a default export arrives under a key called default. It is how code splitting works.
EXERCISE
1A Function, Not a Statement
The static form is a declaration the parser reads. The dynamic form is an expression you call.
The difference in shape:
// Static: a declaration. Hoisted, top level only, path must be a literal.
import { chart } from "./chart.js";
// Dynamic: an expression. Anywhere, any path, returns a promise.
const { chart } = await import("./chart.js");
import() looks like a function call and behaves like one, with one exception: it is not a real function, so you cannot store it in a variable or pass it around. The parser treats import( specially, which is what lets a bundler see which modules might be needed.
It resolves to the module namespace object:
// math.js
export const PI = 3.14159;
export default function add(a, b) {
return a + b;
}
const math = await import("./math.js");
console.log(math.PI); // 3.14159
console.log(math.default); // [Function: add]
console.log(math.add); // undefined
A default export arrives under the key default. This catches everyone once, because the static form hides it:
// These are the same module, two ways in:
import add from "./math.js";
const { default: add } = await import("./math.js");
Which means the destructuring rename is the normal shape:
const { default: Chart, PI } = await import("./chart.js");
The path can be computed, which the static form forbids:
async function loadLocale(lang) {
const messages = await import(`./locales/${lang}.js`);
return messages.default;
}
const en = await loadLocale("en");
A bundler cannot know which locale you will pick, so it usually bundles every file matching that pattern into separate chunks and loads the right one at runtime. That is a feature rather than a limitation, but it is worth knowing that a fully dynamic path such as import(userInput) defeats bundling entirely and is also a security problem.
And it can go anywhere, including inside a condition:
if (user.hasProFeatures) {
const { advancedEditor } = await import("./advanced-editor.js");
advancedEditor.mount();
}
button.addEventListener("click", async () => {
const { openDialog } = await import("./dialog.js");
openDialog();
});
Neither of those is possible with the static form. Nobody who never opens the dialog pays for its code.
Remember default is a key on the namespace object and the rename destructure becomes automatic: const { default: Thing } = await import(...). Forgetting it produces an undefined that looks like a broken module rather than a naming mistake, which is why it costs people more time than it should.
EXERCISE
2Code Splitting, and When It Is Worth It
Every dynamic import is a decision to trade a smaller first load for a later request.
A bundler turns each import() into a separate file and fetches it on demand. That is code splitting, and it is the main reason the feature exists.
What it buys:
// Static: the chart library is in the main bundle whether or not
// the user ever opens the analytics tab. Perhaps 200KB.
import { renderChart } from "./charts.js";
// Dynamic: loaded only when the tab is opened.
async function showAnalytics() {
const { renderChart } = await import("./charts.js");
renderChart(data);
}
For a user who never visits that tab, the second version is 200KB they never download, on a connection you do not control.
What it costs:
// The first click now waits for a network request that the
// static version had already paid for during the initial load.
button.addEventListener("click", async () => {
const { openDialog } = await import("./dialog.js"); // 200ms of nothing
openDialog();
});
The delay lands at the worst moment: immediately after a user action, when they are waiting and watching. Static loading pays the cost during initial load, when they expect to wait.
Which is why the common fix is to preload rather than to choose:
button.addEventListener("mouseenter", () => {
import("./dialog.js"); // start fetching, ignore the result
});
button.addEventListener("click", async () => {
const { openDialog } = await import("./dialog.js"); // already cached
openDialog();
});
The module registry caches by path, so the second call returns the already-resolved promise rather than fetching again. Hovering is usually several hundred milliseconds before clicking, which is enough.
And a loading state is not optional:
async function showAnalytics() {
setLoading(true);
try {
const { renderChart } = await import("./charts.js");
renderChart(data);
} catch (err) {
showError("Could not load the chart module");
} finally {
setLoading(false);
}
}
A dynamic import is a network request and can fail: offline, a deploy that removed the old chunk, an ad blocker. A static import cannot fail at runtime, because if it were missing the application would never have started. That difference is easy to forget.
A rough guide to what is worth splitting:
// Worth it: a route the user may never visit, a heavy library
// behind one feature, an admin panel, a rich text editor.
//
// Not worth it: anything under about 10KB, anything needed on
// first paint, anything most users will reach anyway.
Splitting something small adds a request and saves almost nothing, and a hundred tiny chunks are slower than one reasonable bundle.
Pro Tip: Preloading on hover or on focus is the cheapest performance win in this area, and it is two lines. It turns the trade-off from "small bundle or fast interaction" into mostly having both, because the fetch happens during the pause between deciding to click and clicking.
EXERCISE
3Import Attributes and Loading Other Things
Modules can now load data as well as code, with a syntax that makes the file type part of the import.
A module specifier used to mean one thing: . That is no longer true, and the mechanism is worth knowing because it changes how configuration and data get into an application.
Importing JSON:
import config from "./config.json" with { type: "json" };
console.log(config.apiUrl);
The with { type: "json" } part is an import attribute. It is not optional, and the reason is security: without it, a could serve JavaScript from a URL your code believed was data, and it would be executed. Making the expected type explicit lets the runtime refuse anything else.
You will see an older spelling in existing code and in slightly older runtimes:
import config from "./config.json" assert { type: "json" };
assert was the original keyword and has been replaced by with. They mean the same thing; the rename happened because the committee wanted the attribute to be able to influence loading, not merely check it afterwards.
The dynamic form takes the same attribute as a second argument:
const config = await import("./config.json", {
with: { type: "json" },
});
console.log(config.default.apiUrl);
Note config.default. has no named exports, so the whole document arrives as the default, which is easy to forget after using the static form.
Why this matters more than it first appears:
// Before: a build step inlined the JSON, or you fetched it at runtime
const config = await fetch("/config.json").then((r) => r.json());
// Now: it participates in the module graph
import config from "./config.json" with { type: "json" };
An imported JSON file is resolved, cached and evaluated like any other module. It is available synchronously once the module has loaded, it cannot be half-loaded, and a bundler can see it.
CSS modules work the same way where supported:
import styles from "./component.css" with { type: "css" };
document.adoptedStyleSheets = [styles];
Support is uneven, so check before relying on it. The pattern is the interesting part: the module system is becoming the single way an application declares what it depends on, whatever form that dependency takes.
One limitation worth knowing:
// You cannot import a file and choose not to evaluate it.
import "./side-effects.js"; // runs the module for its side effects
An import with no bindings still evaluates the module. That is occasionally what you want, such as a polyfill or a registration file, and it is a common source of surprise when a file does something merely because it was imported.
