Package Management with npm

A package manager handles installing, updating, and removing third-party libraries (called packages) in your projects. It also manages your project’s metadata, scripts, and dependency tree. npm (Node Package Manager) comes bundled with Node.js and is the default package manager for the JavaScript ecosystem.

Initializing a Project with npm init

Every project starts with a package.json file. This file describes your project and tracks its dependencies. You create one with npm init:

# Create package.json with default settings
npm init -y

# Or answer prompts interactively
npm init

The -y flag accepts all defaults and gives you something like this:

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Installing Packages with npm install

The npm install command (or npm i for short) is how you add packages to your project:

# Install a production dependency
npm install lodash

# Install a development dependency
npm install --save-dev jest

# Install globally (available system-wide)
npm install -g typescript

# Install a specific version
npm install lodash@4.17.21

# Install everything listed in package.json
npm install

That last form is what you run after cloning someone else’s project. It reads package.json and installs everything the project needs.

Production vs. Development Dependencies

When you install a package, it goes into one of two sections of package.json:

{
  "dependencies": {
    "express": "^4.18.2",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "jest": "^29.5.0",
    "eslint": "^8.40.0"
  }
}
  • dependencies are required at runtime. Your app needs these to function.
  • devDependencies are only needed during development: things like test runners, linters, and build tools. They do not ship with your production code.

Common npm Commands

Command Description
npm install Install all dependencies from package.json
npm install <pkg> Add a production dependency
npm install -D <pkg> Add a development dependency
npm uninstall <pkg> Remove a package
npm update Update packages to latest compatible versions
npm outdated Show which packages have newer versions
npm list Show installed packages
npm audit Check for known security vulnerabilities
npm run <script> Run a script defined in package.json

Automating Tasks with npm Scripts

The "scripts" field in package.json lets you define custom commands for your project. This is where you put your build, test, and dev commands:

{
  "scripts": {
    "start": "node server.js",
    "dev": "node --watch server.js",
    "build": "webpack --mode production",
    "test": "jest",
    "lint": "eslint src/",
    "format": "prettier --write src/"
  }
}

Run them with npm run:

npm run dev
npm run lint

test and start are special. They do not need the run keyword:

npm test
npm start