Getting Started

Basic npm commands and workflow for beginners

tutorial

Getting Started with npm

Basic npm commands and workflow for beginners.

What is npm?

npm (Node Package Manager) is the default package manager for Node.js. It allows you to:

  • Install and manage JavaScript packages
  • Share your own packages
  • Manage project dependencies
  • Run scripts and commands

Basic Commands

Initialize a New Project

Create a new package.json file:

npm init

Or use the default values:

npm init -y

Install Packages

Install a package locally (for your project):

npm install package-name
# or
npm i package-name

Install a package globally:

npm install -g package-name

Install a development dependency:

npm install --save-dev package-name
# or
npm i -D package-name

Package Management

View installed packages:

npm list

Update packages:

npm update

Remove packages:

npm uninstall package-name

Understanding package.json

The package.json file is the heart of any Node.js project:

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "My awesome project",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Key Fields:

  • name: Your package name
  • version: Semantic version (semver)
  • scripts: Custom commands you can run with npm run
  • dependencies: Packages required in production
  • devDependencies: Packages only needed during development

Running Scripts

Execute custom scripts defined in package.json:

npm run script-name

Common scripts:

npm start          # Runs the "start" script
npm test           # Runs the "test" script
npm run build      # Runs the "build" script

Semantic Versioning

npm uses semantic versioning (semver) for package versions:

  • Major.Minor.Patch (e.g., 1.2.3)
  • Major: Breaking changes
  • Minor: New features (backward compatible)
  • Patch: Bug fixes (backward compatible)

Version Ranges:

{
  "dependencies": {
    "express": "^4.18.0",    // Compatible with 4.x.x
    "lodash": "~4.17.21",   // Compatible with 4.17.x
    "react": "18.2.0"        // Exact version
  }
}

Best Practices

1. Use Specific Versions in Production

npm install package-name@1.2.3

2. Keep package-lock.json in Version Control

The package-lock.json file ensures consistent installs across environments.

3. Use .npmignore

Create a .npmignore file to exclude files from your package:

node_modules/
*.log
.env

4. Regular Updates

npm outdated    # Check for outdated packages
npm update      # Update to latest compatible versions

Common Workflows

Starting a New Project

mkdir my-project
cd my-project
npm init -y
npm install express
npm install --save-dev nodemon

Adding a New Dependency

npm install axios

Running Your Application

npm start

Next Steps

Resources