Lesson 7 of 20

NPM & Package Management

Installing and Managing Packages

npm (Node Package Manager) is the world's largest software registry with over 2 million packages. It comes bundled with Node.js and lets you install, update, and manage third-party libraries for your projects.

When you install a package, npm downloads it to a node_modules folder and records it in your package.json. This way, anyone who clones your project can run npm install to get all the same packages.

Example
# Install a package (adds to dependencies)
npm install express
npm i express          # Shorthand

# Install a dev-only package
npm install --save-dev nodemon
npm i -D nodemon       # Shorthand

# Install globally (CLI tools)
npm install -g typescript

# Install all dependencies from package.json
npm install

# Uninstall a package
npm uninstall express

# Update packages
npm update

# Check for outdated packages
npm outdated

# List installed packages
npm list --depth=0
  • dependencies — Packages needed in production (express, mongoose)
  • devDependencies — Packages only needed during development (nodemon, jest)
  • node_modules/ — Folder where packages are installed (never commit this)
  • package-lock.json — Locks exact versions for reproducible installs
  • .gitignore — Always add node_modules/ to your .gitignore file
Notes
  • Never commit the node_modules folder to git. It can contain thousands of files. Add 'node_modules/' to your .gitignore file.

NPM Scripts and npx

NPM scripts let you define custom commands in your package.json. They are shortcuts for running common tasks like starting your app, running tests, or building for production.

npx is a tool that comes with npm and lets you run packages without installing them globally. It is especially useful for one-time commands and CLI tools.

Example
// package.json scripts section
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest",
    "build": "tsc",
    "lint": "eslint src/",
    "seed": "node scripts/seed.js"
  }
}

// Running scripts
// npm start          — Runs "node server.js"
// npm test           — Runs "jest"
// npm run dev        — Runs "nodemon server.js"
// npm run lint       — Runs "eslint src/"

// npx — Run packages without global install
// npx create-react-app my-app
// npx eslint --init
// npx nodemon server.js
  • npm start — Run the 'start' script (no 'run' keyword needed)
  • npm test — Run the 'test' script (no 'run' keyword needed)
  • npm run — Run any custom script
  • npx — Execute a package binary without installing globally
  • Pre/Post scripts — npm automatically runs prescript and postscript hooks
Notes
  • Only 'start' and 'test' can be run without the 'run' keyword. All other scripts require 'npm run '.