Sub topic 10
Loading Code on Demand with import()
This chapter assumes you know static import and export, module namespace objects, and async/await. A static import declaration loads its module before any of your code runs. Sometimes you want to wait instead: load a heavy charting library only when the user asks for a chart, or pick a translation file based on settings. The import() expression does this.
The working model
import(specifier) looks like a function call, but it is special syntax. It returns a promise. The promise resolves to the module's namespace object, which is the same object import * as ns would give you.
- Named exports appear as properties of the namespace object.
- The default export appears as the property
default. - The specifier can be any expression, so you can build it at runtime.
import()also works in classic scripts, which cannot use staticimport.
// chart.js
export default function renderChart(container) {
container.textContent = 'Chart rendered';
}
// main.js
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { default: renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});The first click fetches, links, and evaluates chart.js. Later clicks get the same cached module instance, so the module's code never runs twice.
Computed specifiers and error handling
In Node.js this module picks a locale file at runtime and falls back if that file is missing:
// greet.mjs (place en.mjs and fr.mjs next to it, each with: export const hello = '...';)
async function loadMessages(locale) {
try {
return await import(`./${locale}.mjs`);
} catch (error) {
console.warn(`No messages for ${locale}, using en`);
return import('./en.mjs');
}
}
const messages = await loadMessages(process.argv[2] ?? 'en');
console.log(messages.hello);If the file cannot be found, fails to parse, or throws during evaluation, the promise rejects. Handle that with try/catch, as above.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling the namespace as a function: `(await import('./chart.js'))()` | `TypeError: ... is not a function` | Use `.default` or destructure `{ default: fn }` |
| Forgetting `await` | You get a pending promise, and its properties are `undefined` | `await` the call or chain `.then()` |
| Assuming each call re-runs the module | Setup code runs once only | Export a function and call it each time you need it |
| Using `import()` for everything | Extra network round trips, and static analysis can't see the dependency | Keep static `import` for code you always need |
Exercise
A module stats.js has export default function mean(xs) {...} and export const version = 2;. Write one line that dynamically imports it and stores the default export in mean and version in v.
Show answer
const { default: mean, version: v } = await import('./stats.js');
Exercise
setup.js contains console.log('setup');. A program calls await import('./setup.js') three times. How many times does "setup" print, and why?
Show answer
Once. The module is evaluated the first time it loads. Later calls resolve to the same cached module instance and do not run it again.