npm Essentials: Installing and Managing Packages

Adam Sturge | Oct 17, 2023 min read

Overview

npm (Node Package Manager) is the default package manager for Node.js. It allows you to install, share, and manage dependencies in your JavaScript projects.

Steps

  1. Initialize a new npm project:
npm init
# For defaults without prompts
npm init -y
  1. Install a package:
# Add to dependencies (runtime)
npm install package-name
# or shorthand
npm i package-name

# Add to devDependencies (development tools)
npm install package-name --save-dev
# or shorthand
npm i package-name -D
  1. Install a specific version:
npm install [email protected]
  1. Install all dependencies from package.json:
npm install
  1. Update packages:
# Update all packages
npm update

# Update specific package
npm update package-name
  1. Remove a package:
npm uninstall package-name
  1. List installed packages:
npm list
# Just top-level packages
npm list --depth=0

Common Issues

  • Permissions errors: You might need to use sudo on Unix-based systems or adjust permissions
  • Package lock conflicts: If working in a team, merge conflicts in package-lock.json can occur
  • Dependency version issues: Some packages may have incompatible version requirements
  • “node_modules is missing”: Run npm install to recreate the folder

Additional Notes

  • The node_modules folder contains all installed packages and should be in your .gitignore
  • package.json lists your dependencies and project metadata
  • package-lock.json ensures consistent installations across machines
  • Global installation: Use the -g flag to install packages globally:
    npm install -g package-name
    
  • npm scripts: Define custom commands in the “scripts” section of package.json:
    "scripts": {
      "start": "node index.js",
      "test": "jest",
      "build": "webpack"
    }
    
    Run them with npm run script-name (or just npm start for the start script)