Tutorials JavaScript npm Basics
Ch 69 / 78
Chapter 69 Intermediate 7 min read JavaScript

npm Basics — Node Package Manager

npm is the world's largest software registry with over 2 million packages. It ships with Node.js and is the standard tool for installing libraries, managing project dependencies, running build scripts, and sharing code with the JavaScript community.

What you'll learn
What npm is and how it works
Installing, updating & removing packages
Understanding package.json in depth
dependencies vs devDependencies
Semantic versioning (semver)
npm scripts & npx command

What is npm?

npm (Node Package Manager) is three things bundled together:

A Registry
A massive public database at npmjs.com that hosts over 2 million open-source JavaScript packages — from tiny utilities to full frameworks.
A CLI Tool
The npm command-line interface lets you install, update, remove, and publish packages from your terminal.
A Website
npmjs.com is the hub for browsing packages, reading documentation, and managing your published packages and organisations.

npm comes pre-installed with Node.js. Verify your installation:

Terminal
# Check Node.js version
node --version
# v20.11.0  (example output)

# Check npm version
npm --version
# 10.2.4  (example output)

# Update npm to the latest version globally
npm install -g npm@latest
Note
npm is not exclusively for Node.js back-end code. Every modern front-end project — React, Vue, Angular, Svelte — uses npm to manage libraries and tooling.
Search
npmjs.com
Install
package
Saved to
package.json
Files in
node_modules
Locked in
package-lock
Import &
use in code

Initialising a Project with npm init

Every npm-managed project starts with a package.json file. You create it by running npm init inside your project folder:

Terminal
# Interactive setup — asks questions one by one
npm init

# Skip all questions and use sensible defaults immediately
npm init -y
# Creates package.json with name, version, description, etc.

The result is a package.json file. Here is a typical one for a small project:

package.json — Annotated
{
  "name": "my-app",             // project name (lowercase, no spaces)
  "version": "1.0.0",          // current version (semver)
  "description": "My JS app",  // short description
  "main": "index.js",          // entry point for require()
  "scripts": {
    "start": "node index.js",   // run with: npm start
    "dev": "nodemon index.js",  // run with: npm run dev
    "build": "vite build",      // run with: npm run build
    "test": "jest"             // run with: npm test
  },
  "dependencies": {
    "axios": "^1.6.8"          // required in production
  },
  "devDependencies": {
    "vite": "^5.2.0",          // only needed during development
    "jest": "^29.7.0"          // only needed during development
  },
  "keywords": ["demo", "js"],
  "author": "K2infocom",
  "license": "MIT"
}

Installing Packages

The npm install command (shorthand: npm i) is what you'll use most. It downloads package files into the node_modules folder and records the dependency in package.json.

Terminal — Install Commands
── Install all dependencies listed in package.json ──────────────
npm install
# (run this after cloning a project — it restores node_modules)

── Install a production dependency ──────────────────────────────
npm install axios
npm install axios lodash  # multiple packages at once

── Install a dev-only dependency (--save-dev or -D) ─────────────
npm install --save-dev vite
npm install -D jest prettier eslint

── Install a specific version ────────────────────────────────────
npm install axios@1.4.0

── Install a package globally (available system-wide) ───────────
npm install -g nodemon
npm install -g create-react-app

── Update a package to its latest allowed version ───────────────
npm update axios

── Remove a package ─────────────────────────────────────────────
npm uninstall axios
npm uninstall --save-dev jest
Pro Tip
Always add node_modules/ to your .gitignore file. It can contain thousands of files but can always be rebuilt by anyone running npm install on the package.json you committed.
Command Shorthand What it does
npm install <pkg> npm i <pkg> Install and add to dependencies
npm install --save-dev <pkg> npm i -D <pkg> Install and add to devDependencies
npm install -g <pkg> npm i -g <pkg> Install globally (system-wide)
npm install npm i Install all deps from package.json
npm uninstall <pkg> npm un <pkg> Remove package + update package.json
npm update <pkg> npm up <pkg> Upgrade to latest allowed version
npm outdated — List packages with newer versions available
npm list npm ls Show installed dependency tree
npm audit — Scan for known security vulnerabilities
npm audit fix — Auto-fix non-breaking vulnerabilities
npm cache clean --force — Clear the local npm cache

dependencies vs devDependencies

npm splits your packages into two buckets in package.json. Understanding the difference matters for production bundle size and deployment:

dependencies
Packages your app needs at runtime in production. Examples: react, axios, express, lodash.
devDependencies
Packages only needed during development — not shipped to end users. Examples: vite, jest, eslint, prettier, typescript.
peerDependencies
Packages a library expects the host project to already have installed. Common in plugin and library packages.
optionalDependencies
Packages that npm will try to install but will not fail if they cannot be found. Useful for platform-specific packages.
Terminal — Installing to Correct Section
// ✅ Runtime dependency — goes into "dependencies"
npm install axios

// ✅ Dev-only tool — goes into "devDependencies"
npm install -D vite
npm install -D eslint prettier jest

// ✅ In production environment, skip devDependencies entirely
npm install --production
// (or set NODE_ENV=production — npm auto-detects it)
⚡
Free Resource
Download our JavaScript Cheat Sheet
Syntax, built-in methods, ES6+ features — all on one page.
Get Sheet

Semantic Versioning (semver)

npm uses Semantic Versioning — a three-part version number: MAJOR.MINOR.PATCH (e.g. 2.4.1). Each part carries a specific meaning:

M
MAJOR — Breaking Change
Incremented when there are incompatible API changes. You may need to update your code when upgrading. e.g. 1.x.x → 2.0.0
m
MINOR — New Feature
Backwards-compatible new functionality is added. Safe to upgrade. e.g. 1.2.x → 1.3.0
P
PATCH — Bug Fix
Backwards-compatible bug fixes only. Always safe to upgrade. e.g. 1.2.3 → 1.2.4

The version range prefixes in package.json control which updates npm will accept:

package.json — Version Range Syntax
"dependencies": {
  // Caret ^ — accepts MINOR and PATCH updates (most common)
  "axios":   "^1.6.8",    // allows 1.7.0, 1.8.x, but NOT 2.0.0

  // Tilde ~ — accepts PATCH updates only (more conservative)
  "lodash":  "~4.17.21",  // allows 4.17.22, but NOT 4.18.0

  // Exact — pin to this exact version, no auto-updates
  "react":   "18.2.0",    // locked — only 18.2.0

  // Greater-than or latest
  "express": ">=4.0.0",   // any version 4.0.0 or above
  "chalk":   "*"           // any version (wildcard — avoid in production)
}
Best Practice
The package-lock.json file records the exact installed version tree. Always commit it to version control — it ensures every developer and your CI/CD pipeline installs identical versions.

npm Scripts — Automating Your Workflow

The "scripts" field in package.json is where you define terminal commands that can be run with npm run <name>. This is how professional teams wire together their entire build pipeline:

package.json — Scripts Examples
{
  "scripts": {
    // Built-in shortcuts — run without the "run" keyword
    "start":   "node server.js",       // npm start
    "test":    "jest --coverage",      // npm test

    // Custom scripts — need "npm run" prefix
    "dev":     "vite",                 // npm run dev
    "build":   "vite build",           // npm run build
    "preview": "vite preview",         // npm run preview
    "lint":    "eslint src/**/*.js",   // npm run lint
    "format":  "prettier --write .",   // npm run format

    // Chain commands with && (run second only if first succeeds)
    "ci":      "npm run lint && npm test && npm run build",

    // Lifecycle hooks (auto-run before/after another script)
    "prebuild":  "echo Building...",      // runs BEFORE npm run build
    "postbuild": "echo Build done!"       // runs AFTER  npm run build
  }
}
Terminal — Running Scripts
# Built-in lifecycle scripts — no "run" needed
npm start
npm test
npm stop
npm restart

# Custom scripts always need "run"
npm run dev
npm run build
npm run lint

# Pass extra arguments after --
npm test -- --watch          # passes --watch to jest
npm run lint -- --fix        # passes --fix to eslint

# List all available scripts
npm run

npx — Execute Packages Without Installing

npx (included with npm 5.2+) lets you run a package's binary directly without installing it globally first. This is perfect for one-off scaffolding tools and CLI utilities:

Terminal — npx Examples
# Scaffold a React app — downloads create-react-app temporarily
npx create-react-app my-app

# Create a Vite project (recommended over CRA)
npx create-vite@latest my-app

# Run a locally installed binary without npm run
npx jest
npx eslint src/

# Run a specific version of a tool without permanently installing it
npx cowsay "Hello from npm!"

# Check if a package is available before running it
npx --yes prettier --write .
Pro Tip
Use npx for project scaffolding tools like create-react-app, create-vite, or create-next-app — this ensures you always get the latest version without polluting your global npm environment.

node_modules & package-lock.json

Two important files/folders that npm creates automatically:

node_modules/
The folder where all installed package files live. Can easily contain 50,000+ files. Never commit it — always add it to .gitignore. Anyone can restore it by running npm install.
package-lock.json
Auto-generated snapshot of the exact dependency tree — including versions of packages your packages depend on. Always commit this file. It guarantees reproducible installs across machines and CI/CD environments.
.npmrc
Optional per-project configuration file. Can set a custom registry, proxy settings, or default flags like save-exact=true to pin all versions by default.
.gitignore — Required Entries
# Always add these to .gitignore in every JS project
node_modules/
dist/
.env
.env.local
.env.production

# Do NOT ignore these — commit them
# package.json      ← defines your dependencies
# package-lock.json ← locks exact versions
Advertisement

npm vs yarn vs pnpm

npm is not the only package manager for JavaScript. Here's how the three most popular options compare:

npm
The default, ships with Node.js. Largest ecosystem, improving rapidly. Workspaces support added in v7. Best choice for most projects.
yarn
Created by Facebook for speed and determinism. Parallel installs, offline mode. Yarn Berry (v2+) adds zero-install support via Plug'n'Play.
pnpm
Content-addressable storage links packages from a shared store — saving disk space dramatically in monorepos. Strictest about phantom dependencies.
Feature npm yarn pnpm
Install speed Good Fast Fastest
Disk usage High High Lowest (shared store)
Lock file package-lock.json yarn.lock pnpm-lock.yaml
Workspaces ✓ (v7+) ✓ ✓ (best-in-class)
Default with Node ✓ Yes ✗ Separate install ✗ Separate install
Which should I use?
Start with npm — it's built-in and fully capable. Move to pnpm if you work in a monorepo or notice slow installs. Avoid mixing managers on the same project (pick one and stick to it).

Try It Yourself

Live Editor
✎ Editor
👁 Preview
Common Mistake
Running npm install <package> without the -D flag for dev tools (ESLint, Prettier, Jest, Vite) adds them to dependencies instead of devDependencies. This bloats your production bundle and confuses deployment tools.
Quick Check — Chapter 69

In "axios": "^1.6.8", what does the caret ^ allow npm to install?

Chapter Summary
  • npm is three things: a CLI tool, a public registry (npmjs.com), and the ecosystem around it. It ships pre-installed with Node.js.
  • Every project starts with npm init -y, which creates a package.json tracking your name, version, scripts, and dependencies.
  • Use npm install <pkg> for runtime deps and npm install -D <pkg> for dev-only tools. Never commit node_modules — always commit package-lock.json.
  • Semver: MAJOR.MINOR.PATCH. The caret ^ allows minor + patch updates; the tilde ~ allows patch only; no prefix pins the exact version.
  • The "scripts" field automates your workflow — npm start and npm test are built-in; all others use npm run <name>.
  • npx runs a package binary without permanently installing it globally — perfect for project scaffolding like create-vite.
  • npm, yarn, and pnpm are all valid choices; npm is recommended for most projects, pnpm for monorepos.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel