Sub topic 1
Recap: Static Imports and the Module Graph
Prerequisites
This chapter assumes you know import/export syntax, promises with async/await, and how to run a module in a browser or in Node.js.
Static Imports Build the Graph Up Front
A static import statement sits at the top level of a module and names a fixed string. Before any code runs, the runtime reads these statements, fetches every dependency, and links them into a module graph. As a result, everything you import statically is loaded at startup, even code the user may never reach.
Where Modules Run
Code is treated as a module only in a module context:
| Environment | How to opt in |
|---|---|
| Browser | `<script type="module">` |
| Node.js | `.mjs` extension, or `"type": "module"` in `package.json` |
The import() Expression
import(specifier) is an expression you can call anywhere. It returns a promise that resolves to the module's namespace object. The file is fetched and evaluated on the first call. Later calls with the same specifier return the cached instance.
Working with the Namespace Object
A namespace object exposes named exports as properties. The default export appears under the property default.
// logger.js
export const LEVELS = { info: 'INFO' };
export default function log(level, msg) {
console.log(`[${level}] ${msg}`);
}// main.mjs
const loggerModule = await import('./logger.js');
const log = loggerModule.default;
const { default: logAgain, LEVELS } = await import('./logger.js');
log(LEVELS.info, 'ready');
console.log(log === logAgain); // true: same cached moduleLoading Code Only When It Is Needed
Lazy loading defers expensive modules until the user actually needs them:
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});Here chart.js costs nothing at startup. The first click fetches and evaluates it, and every later click reuses the cached module.
Exercise
A module math.js has export default function add(a, b) and export const PI = 3.14. Write one line that dynamically imports it and binds add and PI.
Show answer
const { default: add, PI } = await import('./math.js');