NPM & Package.json

NPM stands for Node Package Manager. It's the world's largest software registry and comes installed by default with Node.js.

1. Initializing a Project

To start using NPM, you need to create a package.json file. This file acts as the manifest for your project.

# Create package.json interactively
npm init

# Create with default values (Quick)
npm init -y

2. Installing Packages

You can install packages locally (for the project) or globally (for your whole system).

# Install locally (Production Dependency)
npm install express

# Install locally as Dev Dependency (Testing/Tools)
npm install nodemon --save-dev

# Install specifically for your machine
npm install -g create-react-app

3. Understanding package.json

Key fields in your package.json:

  • version: Your application's version.
  • scripts: Shortcuts for terminal commands (e.g., npm start).
  • dependencies: Packages required for the app to run.
  • devDependencies: Packages only needed during development.

4. NPM Scripts

You can define custom commands in the scripts section.

"scripts": {
  "start": "node app.js",
  "dev": "nodemon app.js",
  "test": "jest"
}

Now you can run npm run dev to start your server with nodemon.

Tip: Never modify the node_modules folder directly. Use NPM commands to add or remove packages to keep your package.json in sync.