fbpx

Package Managers (npm, yarn)

Package managers are tools that simplify the process of managing and installing software libraries or packages in a programming language-specific ecosystem. They help developers handle dependencies, versioning, and project structure. Two popular package managers for JavaScript and its ecosystem are npm (Node Package Manager) and Yarn.

npm (Node Package Manager):

  1. Installation:
  • npm is included with Node.js. When you install Node.js, npm is automatically installed.
  1. Initialize a Project:
  • Create a package.json file for your project by running: npm init
  1. Install Packages:
  • Install dependencies listed in package.json: npm install
  • Install a specific package and save it as a dependency: npm install package_name
  • Install a development dependency: npm install --save-dev package_name
  1. Global Installation:
  • Install a package globally: npm install -g package_name
  1. Scripts:
  • Define and run scripts in package.json: "scripts": { "start": "node server.js", "test": "mocha" }
  • Run scripts: npm run start
  1. Versioning:
  • Update a package: npm update package_name
  • Install a specific version: npm install package_name@version_number

Yarn:

  1. Installation:
  • Install Yarn globally: npm install -g yarn
  1. Initialize a Project:
  • Create a package.json file for your project: yarn init
  1. Install Packages:
  • Install dependencies: yarn
  • Install a specific package and save it as a dependency: yarn add package_name
  • Install a development dependency: yarn add --dev package_name
  1. Global Installation:
  • Yarn does not have a dedicated global installation command. Instead, it relies on local installations.
  1. Scripts:
  • Define and run scripts in package.json: "scripts": { "start": "node server.js", "test": "mocha" }
  • Run scripts: yarn run start
  1. Versioning:
  • Update a package: yarn upgrade package_name
  • Install a specific version: yarn add package_name@version_number

Yarn vs. npm:

  • Performance:
  • Yarn tends to be faster than npm, especially for dependency resolution and installation.
  • Deterministic Dependency Resolution:
  • Yarn uses a lock file (yarn.lock) for deterministic dependency resolution, ensuring consistent installations across different environments.
  • Offline Mode:
  • Yarn has better support for offline installations and caching.
  • Workspaces:
  • Yarn supports workspaces, allowing you to manage multiple packages within a single repository.
  • Parallel Installation:
  • Yarn installs packages in parallel, making use of parallel processing capabilities.

In general, both npm and Yarn are widely used and serve similar purposes. The choice between them often comes down to personal preference and specific project requirements. Some projects may specify a preference for one over the other, so it’s essential to be familiar with both package managers.