Summary - ES modules
Build a lazily-loaded module structure using dynamic import and re-export.
Summary - ES modules
In this group you met the advanced features of ES modules: loading at runtime with await import(), renaming with as, forwarding with export ... from, module info with import.meta, and name resolution with import maps.
Used together, you can split large apps into small pieces, load code only when needed, and call external libraries by short names.
Exercise Load a module at runtime and use it
Load the ./report.js module at runtime with await import() and assign it to a variable named report. Then log the result of report.build() with console.log.
Show example solution
Load with await import, assign to report, then call build.
Example solution:
const report = await import('./report.js');
console.log(report.build());
Putting it together
A barrel module gathers values with re-export; a consumer picks the ones it needs from a single entry. A heavy piece is loaded on demand with await import().
// index.js
export { login } from './user.js';
// app.js
const user = await import('./index.js');This keeps distribution in one place and keeps heavy code out of the first load.
Exercise Write a two-module barrel
Write an index.js barrel module. Forward login from ./user.js and token from ./session.js on separate export ... from lines.
Show example solution
Write two separate export ... from lines.
Example solution:
export { login } from './user.js';
export { token } from './session.js';
Test yourself
-
Which is best for loading a module only when needed?
- await import('./m.js')
- import { x } from './m.js'
- export { x } from './m.js'
- import.meta.url
Show answer
await import('./m.js') — Correct! await import() loads the module when it is called.
-
Match the features
- await import()
- lazy-loads
- as
- renames
- export ... from
- forwards
- import.meta.url
- gives the address