Yarn 2 (Berry)

YARN 2 (Berry) - The Modern Package Manager 🧶

Yarn 2, also known as Berry, is a significant evolution of the original Yarn package manager. It brings improved performance, enhanced security, and new features to JavaScript and Node.js development.

Architecture and Concepts 🏗️

Yarn 2's architecture is designed for efficiency, reliability, and improved developer experience:

  • 📁 Plug'n'Play (PnP): A new resolution strategy that replaces node_modules

  • 🔒 Zero-Installs: Allows committing dependencies to version control

  • 🌐 Workspaces: Improved monorepo support

  • 🔧 Constraints: Enforce rules across your project

  • 📦 Protocols: Flexible ways to fetch packages

Key Concepts:

  • 🚀 Performance: Faster installs and reduced disk usage

  • 🔐 Security: Improved package resolution and validation

  • 🛠️ Extensibility: Plugin system for custom functionality

  • 📜 TypeScript Support: Better integration with TypeScript projects

Yarn 2 Architecture Diagram 📊

Common Yarn 2 Commands 🖥️

Installation:

npm install -g yarn
yarn set version berry

Initialize a new project:

yarn init -2

Add a dependency:

yarn add [package-name]
yarn add [package-name]@[version]
yarn add -D [package-name]  # Add as dev dependency

Remove a dependency:

yarn remove [package-name]

Install all dependencies:

yarn install

Run a script:

yarn [script-name]

Update packages:

yarn up
yarn up [package-name]

Code Snippets 💻

Example package.json:

{
  "name": "my-yarn2-project",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "typescript": "^4.5.4"
  },
  "scripts": {
    "start": "ts-node src/index.ts",
    "build": "tsc",
    "test": "jest"
  }
}

Example TypeScript file (src/index.ts):

import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World from Yarn 2 project!');
});

app.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}`);
});

Running the application:

yarn start

Output:

Server running at <http://localhost:3000>

Deployment Commands 🚀

Here are some common deployment commands:

Build for production:

yarn build

Run tests before deployment:

yarn test

Start in production mode:

yarn start:prod

Add these scripts to your package.json:

{
  "scripts": {
    "build": "tsc",
    "test": "jest",
    "start:prod": "NODE_ENV=production node dist/index.js"
  }
}

Conclusion 🎉

Yarn 2 (Berry) is a powerful and efficient package manager for Node.js projects. Its innovative features like Plug'n'Play and Zero-Installs provide significant improvements in performance and project management. By leveraging Yarn 2's capabilities, developers can create more efficient, secure, and maintainable JavaScript and TypeScript applications.

Last updated

Was this helpful?