Package Managers in JavaScript (npm vs Yarn)
Package managers are essential tools in modern JavaScript development. They allow you to install, update, remove, and manage third-party libraries or dependencies in your project.
The two most popular package managers are:
- npm (Node Package Manager)
- Yarn (developed by Facebook)
What is a Package?
A package is a prewritten JavaScript library or tool (e.g., React, Axios, Lodash) that you can install into your project using a package manager.
1. npm (Node Package Manager)
Installed automatically with Node.js
To check:
node -v
npm -v
Initialize a project:
npm init -y
Creates a package.json file that holds your project info and dependencies.
Install a package:
npm install axios
Install as a development dependency:
npm install eslint --save-dev
Remove a package:
npm uninstall axios
2. Yarn – Fast & Secure Alternative
Install Yarn:
npm install --global yarn
Initialize project:
yarn init -y
Add a package:
yarn add axios
Add dev dependency:
yarn add eslint --dev
Remove a package:
yarn remove axios
Files Created by npm/Yarn
File | Purpose |
---|---|
package.json | Lists project dependencies, scripts, and metadata |
package-lock.json / yarn.lock | Locks exact versions of dependencies |
node_modules/ | Contains installed packages |
Script Examples in package.json
"scripts": {
"start": "node index.js",
"lint": "eslint .",
"dev": "nodemon index.js"
}
Run with:
npm run start
# or
yarn start
npm vs Yarn – Key Differences
Feature | npm | Yarn |
---|---|---|
Speed | Slower | Faster (caching) |
Lock File | package-lock.js on | yarn.lock |
Offline Install | Limited | Yes |
Plug'n'Play | No | Yes (Yarn v2+) |