Sub topic 1
What Makes a File a Module
Prerequisites
This chapter assumes you know core JavaScript syntax, including destructuring. You should know how let, const, and var differ, and how to run code in a browser or with Node.js.
Module Scope and Strict Mode
An ES module is a file that the runtime loads as a module rather than as a classic script. Three rules set it apart:
- Top-level variables stay private to the file. They do not become globals.
- Strict mode is always on, so assigning to an undeclared variable throws an error.
importandexportmust appear at the top level. The engine can therefore read the dependency graph before it runs any code.
Named Exports
A named export publishes a binding under its own name. You can mark declarations inline or list them at the end. An export list can also rename a binding.
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}
function circumference(radius) {
return 2 * PI * radius;
}
export { circumference as perimeter };Default Exports
A module can have at most one default export. A default export suits a module built around one main thing, such as a single function or class. Named exports work better when a module offers several related tools, because the names stay the same in every importer.
// logger.js
export default function log(message) {
console.log(`[app] ${message}`);
}
export const level = 'info';Import Forms
// main.js
import log, { level } from './logger.js'; // default + named
import * as math from './math.js'; // namespace object
import { area as circleArea } from './math.js'; // renamed
log(`level=${level}`);
console.log(math.PI, circleArea(2));The importer chooses the name of a default import. A named import must match the exported name unless you rename it with as.
Module Specifiers
The string after from is the module specifier. It comes in three kinds:
| Specifier | Example | Resolves to |
|---|---|---|
| Relative | `'./math.js'` | A file next to the importing module |
| Absolute URL | `'https://example.com/a.js'` | That exact URL |
| Bare | `'lodash-es'` | A package (Node.js) or an import map entry (browser) |
Exercise
A file contains export default 42; and export const x = 1;. Write one import statement that binds the default as answer and the named export as x.
Show answer
import answer, { x } from './file.js';
Exercise
Why does import { circumference } from './math.js' fail with the math.js shown above?
Show answer
circumference is exported only under the name perimeter, so the import must be { perimeter } or { perimeter as circumference }.