Web Development · Module 8 · Lesson 21 min read

npm & package.json

npm: Node's package manager

npm installs packages (libraries) from the npm registry, which has millions of them.

Terminal
npm init -y                 # create package.json
npm install dayjs           # add a dependency
npm install -D vite         # add a dev-only dependency
npm uninstall dayjs
npm run dev                 # run a script from package.json

package.json

JSON
{
  "name": "my-app",
  "type": "module",
  "scripts": { "dev": "vite", "build": "vite build" },
  "dependencies": { "dayjs": "^1.11.10" },
  "devDependencies": { "vite": "^5.0.0" }
}
  • dependencies are needed when the app runs; devDependencies are only for building and testing.
  • scripts are shortcuts run with npm run <name>.

Versions (semver: MAJOR.MINOR.PATCH)

  • ^1.11.10 allows updates up to (but not including) 2.0.0.
  • ~1.11.10 allows only patch updates (1.11.x).
  • package-lock.json records the exact installed versions. Commit it, so everyone installs the same thing.

node_modules

The folder where packages are installed. It's huge: never commit it (add it to .gitignore); npm install recreates it.

Tips

  • Check a package's downloads, last update and size before adding it.
  • npm audit lists known security issues.
  • Alternatives: pnpm (faster, saves disk space), yarn, bun.

Example

Terminal
# Start a project
mkdir my-app && cd my-app
npm init -y

# Add packages
npm install dayjs
npm install -D vite

# .gitignore
echo "node_modules/" >> .gitignore

# package.json → "scripts": { "dev": "vite", "build": "vite build" }
npm run dev
# 💻 Terminal commands — run them on a computer with Node.js installed