Sikau

Node.js · Day 2 · about 30 min

Modules and npm

Split code into files; use other people's packages.

One file is never enough

Real programs are split into modules — files that export functions and import each other. And the npm registry holds millions of ready-made packages you can install with one command.

ES modules (and CommonJS)

import { formatPrice, TAX } from "./lib/money.js";
import menu from "./data/menu.js";

for (const dish of menu) {
  console.log(dish.name, formatPrice(dish.price * (1 + TAX)));
}
  • "type": "module" in package.json turns on ES modules (import/export) — the modern standard.
  • Older code uses CommonJS: const fs = require("fs") and module.exports = …. You'll see both.
  • Built-in modules use the node: prefix: import fs from "node:fs".
  • npm install express adds a package to node_modules/ and package.json dependencies; npm run start runs a script.
  • Commit package.json and package-lock.json; never commit node_modules/.

The rest of this lesson

  • Exports, named and defaultexplain
  • Living with npm packagesexplain
  • What's imported?predict
  • Which file?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js