npm & package.json

npm (Node Package Manager) is the default package manager for Node.js. It helps you install, manage, and share reusable code packages (modules) for your JavaScript projects.

Illustration of npm & package.json
Illustration of npm & package.json

💡 What is package.json?

A package.json file is a manifest that records metadata about your project and its dependencies. It allows npm to track and manage packages your project needs.

Why Use npm?

  • Install third-party libraries easily.
  • Manage project dependencies and their versions.
  • Run scripts to automate tasks.
  • Publish your own packages to share with others.

Creating a package.json

Run the command below in your project folder to create package.json interactively:

📌 Deep Dive: Initializing package.json

SHELL
npm init

Or add -y to generate with defaults:

📌 Deep Dive: Quick package.json generation

SHELL
npm init -y

Key Fields in package.json

Common package.json Properties
FieldDescription
nameProject or package name
versionProject version
descriptionBrief summary of the project
mainEntry point file (e.g., index.js)
scriptsCommands to automate tasks (e.g., start, test)
dependenciesLibraries required to run the project
devDependenciesLibraries only needed during development
authorProject author information
licenseProject license type

Installing Packages

Add packages to your project with:

📌 Deep Dive: Installing a package

SHELL
npm install lodash

This installs lodash and adds it to dependencies in package.json.

To install a package only for development (e.g., testing libraries):

📌 Deep Dive: Installing a devDependency

SHELL
npm install --save-dev jest

Running Scripts from package.json

Scripts automate commands in your project. Example:

📌 Deep Dive: Adding and running a script

JSON
{
  "scripts": {
    "start": "node index.js",
    "test": "jest"
  }
}

Run scripts with:

npm run start
npm test

⚠️ Important:

Always commit your package.json and package-lock.json files to version control. Do NOT commit node_modules folder.

Summary

  • npm is the package manager used to install and manage JavaScript packages.
  • package.json defines project metadata, dependencies, and scripts.
  • Use npm install to add packages and update package.json.
  • Scripts in package.json help run common tasks easily.