Sub topic 3
The import() Expression
This chapter assumes you know static import and export syntax, can read code that uses promises and async/await, and have run ES modules in a browser or in Node.js.
What import() Is
import() is an expression that loads a module at runtime and returns a promise. When the module has been fetched, linked, and evaluated, the promise resolves to that module's namespace object. A namespace object is a frozen object that holds the module's exports.
It looks like a function call, but import is a keyword. That has some consequences:
- You cannot assign it to a variable (
const load = importis a syntax error). - You cannot call it with
.call()or.apply(), and you cannot pass it around as a callback. - It can appear anywhere an expression can: inside functions,
ifblocks, loops, and event handlers.
Static import declarations are different. They must sit at the top level of a module, and they are processed before any code in the module runs.
Static vs. Dynamic at a Glance
| Feature | Static `import` | `import()` |
|---|---|---|
| Position | Top level of a module only | Anywhere an expression is allowed |
| Specifier | String literal | Any expression that evaluates to a string |
| When it loads | Before the importing module runs | When the expression is evaluated |
| Result | Bindings in scope | Promise for the namespace object |
| Available in classic scripts and CommonJS | No | Yes |
The last row matters in practice. import() works in a classic <script> tag and in CommonJS files. You do not need to be inside an ES module to load one.
A First Example
Create two files in the same folder.
// math.js
export function square(n) {
return n * n;
}
export const PI = 3.14159;// main.mjs
console.log('before import');
const mathPromise = import('./math.js');
console.log('promise created:', mathPromise instanceof Promise);
const math = await mathPromise;
console.log(math.square(4), math.PI);For Node.js to treat math.js as an ES module, add a package.json containing { "type": "module" } to that folder, or rename the file to math.mjs and update the specifier. Run node main.mjs and you get:
before import
promise created: true
16 3.14159The await at the top level of main.mjs is top-level await, which a later chapter covers. Inside a regular function you would write const math = await import('./math.js') in an async function, or chain .then() on the promise.
What Happens When import() Runs
Each module is evaluated at most once per realm, meaning per page or per Node.js process. Calling import('./math.js') ten times starts one fetch and one evaluation, and every promise resolves to the same namespace object. The module's top-level code does not run again.
Common Mistakes
- Forgetting the promise.
const m = import('./math.js'); m.square(2)throws a TypeError, becausemis a promise and has nosquareproperty. - Expecting synchronous loading. Code after a non-awaited
import()runs before the module has loaded. - Treating it as a function.
[a, b].map(import)is a syntax error. Wrap it instead:specs.map((s) => import(s)).
Exercise
A module counter.js contains console.log('loaded'); export let count = 0;. Another module runs const a = await import('./counter.js'); const b = await import('./counter.js'); console.log(a === b);. What is printed, and why?
Show answer
It prints "loaded" once, then "true". The first import() fetches and evaluates counter.js and stores it in the module map. The second call finds the cached module, so the top-level code does not run again, and both promises resolve to the same namespace object.
Exercise
Why does const loader = import; fail while const loader = (s) => import(s); works?
Show answer
import is a keyword with special syntax, not a function value, so it cannot be referenced on its own. Wrapping the import() expression in an arrow function creates an ordinary function that you can store and pass around.