Modules & npm: Standing on Shoulders

Modules & npm: Standing on Shoulders in JavaScript: No serious app is built entirely from scratch — you borrow code.

Concept Explanation

No serious app is built entirely from scratch — you borrow code. npm (Node Package Manager) is a giant warehouse of over two million free packages: date libraries, web frameworks, test tools. You "order" a part and it shows up in a folder called node_modules, ready to import.

Every Node project has a package.json — the receipt that lists exactly which packages (and which versions) your app depends on. Share that one file and anyone can rebuild the whole node_modules folder with a single command.


Syntax or Core Structure

npm init -y                     # create a package.json
npm install express             # download a package + record it
npm install --save-dev vitest   # a dev-only dependency

Then use it in code:

import express from "express"; // ES Modules
// or, in CommonJS:
const express = require("express");

Real World Example

The Lockfile: Alongside package.json, npm writes package-lock.json — it pins the exact version of every nested dependency so your teammate's install is byte-for-byte identical to yours. Reproducible builds, no "works on my machine."


Common Mistakes

  • Committing node_modules: It can be hundreds of megabytes. Add it to .gitignore — the lockfile is enough to rebuild it.
  • Ignoring Semver: ^1.2.0 allows minor updates; ~1.2.0 only patches. Misreading these breaks builds.
  • Global Installs Everywhere: Prefer local project installs so each project controls its own versions.

Best Practices

  • Commit the Lockfile: Always check in package-lock.json for reproducible installs.
  • Audit Dependencies: Run npm audit to catch known security holes.
  • Fewer Dependencies: Every package is code you didn't review. Don't add a library to save three lines.

Practice Exercises

  1. The Setup: Run npm init -y and install any package. Inspect the new package.json.
  2. The Script: Add a "start": "node index.js" entry to the scripts section and run it with npm start.
  3. The Detective: Open package-lock.json and explain why it's so much longer than package.json.