Modules
Import and export.
Real programs have thousands of lines. Putting them all in one file would be chaos. Modules let you split code into files, and share only what you choose, with export and import.

- Thousands of lines
- One file is chaos
- Modules: export and import
Two files
A separate file, utils dot MJS, exports a constant, a function, and a default function. In our app, import pulls them in. Named exports go in curly braces, and the default export can be given any name. Run it.
import formatMoney, { TAX, withTax } from "./utils.mjs";
const price = 50;
console.log("Tax rate:", TAX);
console.log("With tax:", formatMoney(withTax(price)));Tax rate: 0.2 With tax: $60.00
Also uses utils.mjs
export const TAX = 0.2;
export function withTax(price) {
return price * (1 + TAX);
}
export default function formatMoney(n) {
return `$${n.toFixed(2)}`;
}Why modules help
Each module has its own scope, so its variables don't leak out unless exported. Files stay small and focused. In Node, files ending in dot MJS use these modules, or you can set type module in package dot JSON. In the browser, a script tag with type equals module does the same.
| key | value |
|---|---|
| export | share from a file |
| import { a } from | named import |
| import x from | default import |
| Own scope | nothing leaks |
Summary
Modules split code into files. Export shares values, and import uses them. Next, working with dates.
Key takeaways- export / export default
- import { } from
- Small, focused files