Sub topic 3
The import() Expression
This chapter assumes you can read import and export declarations, work with promises and async/await, and run a file as an ES module in a browser or in Node.js (for example, by giving it the .mjs extension). The examples use Node.js file names, but the behavior described here is the same in browsers.
Static import declarations are fixed before your code runs. The runtime reads them, fetches every dependency, links them together, and only then starts evaluating. The import() expression works on a different schedule. It runs when the line containing it executes, and it gives back a promise. This chapter covers what the expression is, its syntax rules, when each loading step happens, and how it differs from the declaration form.
What import() Is
import() is an expression that asks the host (the browser or Node.js) to load a module at runtime. It returns a promise. The promise fulfills with the module's namespace object, which is an object whose properties are the module's exports. If loading fails, the promise rejects.
// math.mjs
export function add(a, b) {
return a + b;
}// main.mjs
import('./math.mjs').then((math) => {
console.log(math.add(2, 3)); // 5
});Run it with node main.mjs. Inside an async function, await reads more clearly:
// main-async.mjs
async function run() {
const math = await import('./math.mjs');
console.log(math.add(2, 3)); // 5
}
run();The namespace object gets its own chapter. Here, treat it as "the object holding the exports."
It Looks Like a Function Call, But It Is Not One
import(...) looks like a call to a function named import, but import is a keyword. The parser recognizes import( as special syntax, the same way it treats super(. That has practical consequences:
// Each of these lines is a SyntaxError on its own:
// const load = import; // import is not a value
// import.call(null, './a.mjs'); // no .call, .apply, or .bind
// new import('./a.mjs'); // cannot be used with new
// import(); // a specifier is requiredIf you need a function you can pass around, such as for dependency injection or for tests, wrap it:
// loader.mjs
export const load = (specifier) => import(specifier);Arguments
The grammar allows one or two arguments, plus an optional trailing comma:
- The first argument is the specifier. It can be any expression. The runtime evaluates it and converts the result to a string.
- The optional second argument is an options object. Today its only standard use is
with, which carries import attributes such as{ with: { type: 'json' } }. A later chapter covers this.
The specifier can be any expression, so a computed specifier like this is valid:
// pick.mjs
const name = process.argv[2] ?? 'math';
const mod = await import(`./${name}.mjs`);
console.log(Object.keys(mod));Running node pick.mjs math prints [ 'add' ]. Computed specifiers have resolution and bundler consequences, which later chapters cover.
The example above uses top-level await, which works in ES modules and has its own chapters. In the rest of this chapter, it appears only where it keeps an example short.
When Each Step Happens
Calling import() starts a pipeline and returns right away. The steps are:
- Evaluate the specifier. This is synchronous. If the expression throws, the promise rejects with that error. It does not throw synchronously at the call site.
- Resolve. The specifier becomes an absolute URL or file path. Relative specifiers resolve against the module or script that contains the
import()expression. - Fetch and parse the target module and, recursively, its static dependencies.
- Link imports to exports across that subgraph.
- Evaluate every module in the subgraph that has not already run, dependencies first.
- Fulfill the promise with the namespace object.
You can watch the timing directly:
// counter.mjs
console.log('3. counter.mjs is evaluating');
export let count = 0;
export function increment() {
count += 1;
}// timing.mjs
console.log('1. before import()');
const pending = import('./counter.mjs');
console.log('2. import() returned', pending instanceof Promise);
pending.then((counter) => {
counter.increment();
console.log('4. count is', counter.count);
});Output of node timing.mjs:
1. before import()
2. import() returned true
3. counter.mjs is evaluating
4. count is 1The target module never runs during the import() call itself, even if it is already on disk or in the HTTP cache. Its evaluation always happens in a later job.
Every Call Returns the Same Module Instance
Each realm keeps a module map. A realm is roughly one page, one worker, or one Node.js process. The module map is keyed by the resolved URL. The first import() of a URL loads and evaluates the module. Later calls, and static imports of the same URL, reuse that one instance. The module's top-level code runs only once.
// same-instance.mjs
const a = await import('./counter.mjs');
const b = await import('./counter.mjs');
console.log(a === b); // true: same namespace object
a.increment();
console.log(b.count); // 1: shared live bindingTwo details follow from the cache being keyed by resolved URL:
'./counter.mjs'and'./counter.mjs?v=2'resolve to different URLs, so they create two separate instances. Cache-busting query strings duplicate module state.- A failed load is not retried in browsers. If the fetch or parse fails, the module map records the failure, and later
import()calls for that URL reject with the same error. A later chapter covers recovery strategies.
Where import() Works
Static import declarations are allowed only in module code. import() is allowed almost everywhere:
| Context | Static `import` | `import()` |
|---|---|---|
| ES module (`type="module"`, `.mjs`, `"type": "module"`) | Yes | Yes |
| Classic browser `<script>` | No | Yes |
| Inside a function, `if`, loop, or `try` block | No | Yes |
| CommonJS file in Node.js | No | Yes |
| `eval` code and module workers | Not in eval; yes in module workers | Yes |
| Browser console / Node.js REPL | No | Yes |
The classic-script row is useful when migrating a legacy page: one ordinary <script> can pull in a modern module graph without being converted itself. Content Security Policy still applies, and the fetched module must be served with a JavaScript MIME type.
Static Declaration vs. Dynamic Expression
| Property | `import x from '...'` | `import('...')` |
|---|---|---|
| Position | Top level of a module only | Anywhere an expression is allowed |
| Specifier | String literal | Any expression, converted to string |
| When loading starts | Before any code in the module runs | When the expression executes |
| Result | Bindings declared in scope | Promise for a namespace object |
| Failure shows up as | Whole module graph fails to load | Rejected promise you can handle |
| Visible to static tools | Fully | Only when the specifier is a literal |
| Bindings | Live, read-only identifiers | Live properties on the namespace object |
The visibility row matters most for tooling. Bundlers, linters, and tree-shakers read static declarations exactly. With import(), they can follow a literal specifier, but they can only guess at a computed one. They also usually cannot tell which exports you will read, so they keep all of them.
Common Mistakes
Forgetting to await
// forgot-await.mjs
const math = import('./math.mjs');
console.log(typeof math.add); // "undefined": math is a PromiseThe fix is const math = await import('./math.mjs') or .then().
Wrapping a synchronous throw in try/catch without await
A bad specifier never throws synchronously, so the following catch block never runs:
// no-catch.mjs
try {
import('./missing.mjs'); // rejection escapes: unhandled
} catch (err) {
console.log('never reached');
}Add await inside the try block, or attach .catch() to the promise.
Expecting `export *` style re-exports from import()
import() hands back a namespace object. It cannot re-export anything. For a facade that forwards another module's exports, use a static export * from or export { x } from.
Mixing static and dynamic imports of one module
If a module is already imported statically somewhere in the graph, a dynamic import of it saves nothing. The module is already loaded and evaluated. Dynamic imports only defer work for modules that nothing has imported statically.
Exercise
In timing.mjs, suppose counter.mjs had already been imported statically by timing.mjs itself (import './counter.mjs'; at the top). What would the output order be, and why?
Show answer
The output would be "3. counter.mjs is evaluating", "1. before import()", "2. import() returned true", "4. count is 1". The static import makes counter.mjs evaluate before any of timing.mjs's code runs. The later import() finds the instance in the module map and does not evaluate it again. It still returns a promise, which fulfills in a later job.
Exercise
Why does const load = import; load('./a.mjs'); fail, and how would you give a test a replaceable loader?
Show answer
import is a keyword. import(...) is special syntax, not a call to a function value, so import alone is a SyntaxError. Export a wrapper such as export const load = (s) => import(s); and let tests substitute their own function. Pass absolute URLs (for example, built with new URL(spec, import.meta.url).href), because relative specifiers resolve against the wrapper's file.
Exercise
A page calls import('./widget.js?v=1') in one place and import('./widget.js?v=2') in another. widget.js keeps a module-level counter. How many counters exist, and how many times does widget.js's top-level code run?
Show answer
There are two counters, and the top-level code runs twice. The module map is keyed by resolved URL, and the query strings make the two URLs differ, so the page creates two independent module instances.