Careeroza
ES Modules
export and import
Modules let you split code into files with their own scope. A module exports what others may use and imports what it needs.
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function circumference(r) { return 2 * PI * r; }
// app.js
import circumference, { area, PI as pi } from "./math.js";
import * as math from "./math.js";
console.log(area(2), circumference(1), math.PI);Named vs Default Exports
| Named export | Default export | |
|---|---|---|
| Per file | many | one |
| Import name | must match (can rename with as) | any name you like |
| Syntax | import { area } from "./m.js" | import area from "./m.js" |
Tip: Many teams prefer named exports: editors can auto-import them and renames are tracked.
Modules in the Browser
<script type="module" src="app.js"></script>
<!-- modules are deferred, strict, and have their own scope -->- Module scripts run in strict mode automatically.
- Top-level variables are not global.
- Each module runs only once, however many times it is imported.
- Modules support top-level
await.