npm and yarn have the same purpose, they are Javascript package managers.
npm is installed as the default manager when we install node on our system, while Yarn, initially developed by Facebook,
is a popular alternative to npm that offers more ore less the same functionality in a different way.
To install Yarn globally, open your terminal and run:
npm i -g yarn
At this time (March 10, 2022) if you launch the command above, version 1.22.17 of yarn is installed, but in reality there is also a version 2 of yarn, with more advanced features and a different api.
On the yarn official site there is excellent documentation about it:
In some projects I use yarn and in others I use npm, sometimes by my choice, sometimes not ...
Here is a reminder for the main commands of both tools.
Command | npm | yarn |
---|---|---|
Install dependencies | npm install | yarn |
Install package | npm install [package] | yarn add [package] |
Install package | npm install [package] --save | yarn add [package] |
Install dev package | npm install --save-dev [package] | yarn add [package] --dev |
Install optional package | npm install --save-optional [package] | yarn add [package] --optional |
Install package specific version | npm install --save-exact [package] | yarn add [package] --exact |
Uninstall package | npm uninstall [package] | yarn remove [package] |
Uninstall dev package | npm uninstall --save-dev [package] | yarn remove [package] |
Update | npm update | yarn upgrade |
Update package | npm update [package] | yarn upgrade [package] |
Global install package | npm install --global [package] | yarn global add [package] |
Global uninstall package | npm uninstall --global [package] | yarn global remove [package] |
Run tests for the current package | npm test | yarn test |
Check for outdated packages | npm outdated | yarn outdated |
Run a script | npm run | yarn run |
Manage local package cache | npm cache clean | yarn cache clean |
Log in or out | npm login/logout | yarn login/logout |
rebuild package | npm rebuild | yarn add --force |
clear npm/yarb cache | npm cache clean | yarn cache clean [package] |