JavaScript Tutorial · Classes and Modules · Lesson 30 of 44
JavaScript Modules
Split code into files with export and import.
Why modules?
Modules let you split a program into files, each with its own scope. A module exports what others may use and imports what it needs.
// math.js
export const PI = 3.14159;
export function circleArea(r) {
return PI * r * r;
}
export default function square(n) {
return n * n;
}
// app.js
import square, { circleArea, PI } from "./math.js";
import * as math from "./math.js";
console.log(square(4)); // 16
console.log(circleArea(1)); // 3.14159
console.log(math.PI); // 3.14159
- A module has any number of named exports and at most one default export.
- Import names must match named exports; you can rename with
import { circleArea as area }.
Using modules
- In the browser:
<script type="module" src="app.js"></script>. - In Node.js: use the
.mjsextension, or set"type": "module"inpackage.json. - Dynamic import:
const mod = await import("./big-feature.js")loads code only when needed.
Older Node.js code uses CommonJS (require() and module.exports). You'll still see it everywhere, but new code should use import/export.
Packages with npm
npm install dayjs downloads a package into node_modules and records it in package.json; then import dayjs from "dayjs".
// A module is just a scope: everything not exported stays private.
const mathModule = (() => {
const PI = 3.14159; // private
const circleArea = (r) => PI * r * r;
return { circleArea }; // the "exports"
})();
console.log(mathModule.circleArea(2));
console.log(mathModule.PI);
Output
12.56636 undefined
Test yourself
How many default exports can a module have?
NoneAt most oneTwoUnlimited
Show answer
Answer: At most one