Sub topic 10
Loading Code on Demand with import()
Static import declarations are fixed. They sit at the top level of a module, they name a literal string, and the engine loads every one of them before any of your code runs. That fixed structure is what makes modules predictable, but it costs you in some cases. Sometimes you don't want to load a charting library until the user asks for a chart. Sometimes the module you need depends on a value you only know at runtime, such as the user's language. Dynamic import() handles both cases.
This chapter assumes you are comfortable with promises and async/await. It also assumes you know the static import forms and that a module's default export lives under the name default, both covered in earlier chapters.
What import() Returns
import(specifier) starts loading a module and returns a promise. The promise resolves to the module's namespace object, the same object you would get from import * as ns from '...'. Named exports are properties of that object, and the default export is the property called default.
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { default: renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});The destructuring { default: renderChart } is needed because default is a reserved word and can't be a variable name. Renaming it during destructuring is the usual idiom.
Note that import() looks like a function call but is special syntax. You can't store it in a variable (const load = import is a syntax error), call it with .call, or pass it as a callback. If you need a reusable loader, wrap it: const load = (path) => import(path);.
How It Differs from Static import
| Aspect | `import ... from` | `import()` |
|---|---|---|
| Where it can appear | Top level of a module only | Any expression, in any function or block |
| Specifier | String literal | Any expression that evaluates to a string |
| When loading happens | Before the module's code runs | When the expression is evaluated |
| Result | Bindings in module scope | Promise for a namespace object |
| Available in classic scripts | No | Yes |
| Bindings | Live, read-only names | Properties on the namespace (also live) |
The last row matters. The namespace object is live in the same way imported bindings are. If the exporting module later changes an exported let, reading ns.count again gives the new value. If you destructure, the local variables are ordinary copies taken at that moment, so they don't update.
The Loading Sequence
The first time you call import() with a given specifier, the engine resolves it, then fetches, parses, and links that module along with its whole static dependency graph, then evaluates the graph. The promise resolves only after evaluation finishes.
Modules are singletons per resolved URL. A second import('./chart.js') from the same realm doesn't fetch or run the module again. It returns a promise for the same namespace object. If a static import elsewhere already loaded the module, import() reuses that instance as well. You can therefore call import() inside a click handler without caching the result yourself.
Resolution Is Relative to the Calling File
A relative specifier passed to import() resolves against the URL of the module that contains the call. It doesn't resolve against the page or the current working directory. Inside a classic script, which has no module URL, it resolves against the document's base URL. Bare specifiers follow the same rules as static imports, so in the browser they need an import map, and in Node.js they go through package resolution.
Computed Specifiers: Loading by Runtime Value
Because the specifier is an expression, you can choose the module at runtime. Here is a complete Node.js example. Save the three files in a folder whose package.json contains "type": "module", then run node main.js fr.
// locales/en.js
export default { greeting: 'Hello', farewell: 'Goodbye' };// locales/fr.js
export default { greeting: 'Bonjour', farewell: 'Au revoir' };// main.js
const SUPPORTED = new Set(['en', 'fr']);
async function loadMessages(locale) {
const safe = SUPPORTED.has(locale) ? locale : 'en';
const module = await import(`./locales/${safe}.js`);
return module.default;
}
const messages = await loadMessages(process.argv[2] ?? 'en');
console.log(messages.greeting);The allow-list is important. When you build a path from user input without checking it, a value like ../secrets can make your program load and execute a file you never meant to expose.
Errors and Rejection
The promise rejects if resolution fails, the fetch fails (network error, 404, file not found), the module or one of its dependencies has a syntax error, linking fails because an imported name doesn't exist, or evaluation throws. Handle these failures like any other rejected promise.
async function loadOptionalPlugin(name) {
try {
return await import(`./plugins/${name}.js`);
} catch (error) {
console.warn(`Plugin "${name}" unavailable:`, error.message);
return null;
}
}A static import failure stops the whole module graph from running. With import(), the failure stays inside the code that asked for the module, so the rest of your application can keep working without it.
Loading Several Modules in Parallel
Each await import() in a row waits for the previous load to finish. When the modules don't depend on one another, start all the loads at once:
const [chartModule, tableModule] = await Promise.all([
import('./chart.js'),
import('./table.js'),
]);
chartModule.default(document.querySelector('#chart'));
tableModule.renderTable(document.querySelector('#table'));Passing Import Attributes
import() takes an optional second argument. Use it to pass import attributes, which play the same role as the with clause on a static import:
const { default: config } = await import('./config.json', {
with: { type: 'json' },
});
console.log(config.name);Bundlers and Code Splitting
Bundlers such as Vite, webpack, Rollup, and esbuild treat import('./chart.js') as a split point. They emit chart.js and its dependencies as a separate chunk and load that chunk over the network only when the call runs. This is the main way front-end apps keep their initial download small.
Bundlers can only split code they can see. A literal string works best. A template literal with a fixed prefix and suffix, such as ` ./locales/${safe}.js , usually works too, because the bundler bundles every file that matches the pattern. A fully computed string such as import(pathFromServer)` can't be analyzed, so the bundler leaves it alone and the file must exist at runtime at that exact URL.
import() from CommonJS
In Node.js, require() historically could not load ES modules. Recent versions can load ES modules that don't use top-level await. import(), however, works everywhere, including inside CommonJS files, so it remains the portable way for a .cjs file to load ES module code:
// report.cjs
async function main() {
const { area } = await import('./math.js');
console.log(area(2));
}
main();Exercise
A module calls import('./stats.js') inside a function that runs three times. stats.js contains a top-level console.log('stats loaded'). How many times is the message printed, and are the three resolved values the same object?
Show answer
The message is printed once. The first call fetches and evaluates stats.js. Later calls reuse the cached module instance for that resolved URL, so all three promises resolve to the same namespace object (=== is true).
Exercise
This code loads two independent modules: const a = await import('./a.js'); const b = await import('./b.js');. What is the performance problem, and how do you fix it?
Show answer
The second load doesn't start until the first has finished, so the two loads run one after the other. Start both at once with const [a, b] = await Promise.all([import('./a.js'), import('./b.js')]); so the fetches overlap.
Exercise
Why does import(\./locales/${userInput}.js\) need validation even when no bundler is involved?
Show answer
import() executes the module it loads. Unchecked input could point the specifier at an unexpected file, for example through ../ segments, and run code the author never intended to expose. Mapping the input to an allow-list of known locales prevents this.