Sub topic 2
When a Dynamic Import Fails
This chapter assumes you know ES module import/export syntax, promises with async/await, and the basics of the import() expression and namespace objects.
Handling Failures
import() returns a promise. The promise rejects if the file is missing, the network fails, or the module throws while it evaluates. You handle that rejection with try/catch, the same way you handle any other awaited rejection:
async function loadMessages(lang) {
try {
const mod = await import(`./locales/${lang}.js`);
return mod.default;
} catch (err) {
console.warn(`Locale "${lang}" failed to load, using English`, err);
const fallback = await import('./locales/en.js');
return fallback.default;
}
}Loading Several Modules at Once
If you await each import in turn, the second fetch waits until the first one finishes. Start every import first and then await them together:
const [{ parse }, { format }] = await Promise.all([
import('./parser.js'),
import('./formatter.js'),
]);
console.log(format(parse('2 + 2')));Specifiers and Resolution
A relative specifier such as ./locales/en.js resolves against the URL of the module that calls import(). It does not resolve against the HTML page or the current working directory. A bare specifier such as 'lodash' only works if something maps it to a file: Node's package resolution, an import map in the browser, or a bundler. Template literals are allowed, because the specifier is computed when the code runs.
How Bundlers Split Code
Bundlers such as webpack, Rollup, and Vite treat each import() as a split point and put the target module in its own chunk. When the specifier is a template literal with a static prefix, like ./locales/${lang}.js, the bundler creates a chunk for every file that matches. When the specifier is a bare variable, the bundler cannot know which files to include, so it can't split the code there.
Top-Level Await
In an ES module, you can use await outside any function. The module pauses its evaluation at that await, and any module that imports it waits until it finishes:
// config.js
const response = await fetch('/config.json');
export const config = await response.json();// main.js
import { config } from './config.js';
console.log(config.apiUrl); // runs after config.js finishesTop-level await only works in modules. Classic scripts and CommonJS files can't use it.
Exercise
Why might import(path), where path is a plain variable, break code splitting, while ` import(./locales/${lang}.js) ` does not?
Show answer
The bundler cannot tell which files a plain variable could point to, so it can't create chunks for them. The static prefix ./locales/ and suffix .js limit the possible files to that folder, so the bundler can make a chunk for each match.
Exercise
Two independent modules take 300 ms each to load. About how long does loading them with two sequential awaits take, compared with Promise.all?
Show answer
About 600 ms with sequential awaits, because the second fetch starts only after the first ends. About 300 ms with Promise.all, because both fetches run at the same time.