npm vs yarn Cheat Sheet

thumbnail

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.

npm & yarn commands

Commandnpmyarn
Install dependenciesnpm installyarn
Install packagenpm install [package]yarn add [package]
Install packagenpm install [package] --saveyarn add [package]
Install dev packagenpm install --save-dev [package]yarn add [package] --dev
Install optional packagenpm install --save-optional [package]yarn add [package] --optional
Install package specific versionnpm install --save-exact [package]yarn add [package] --exact
Uninstall packagenpm uninstall [package]yarn remove [package]
Uninstall dev packagenpm uninstall --save-dev [package]yarn remove [package]
Updatenpm updateyarn upgrade
Update packagenpm update [package]yarn upgrade [package]
Global install packagenpm install --global [package]yarn global add [package]
Global uninstall packagenpm uninstall --global [package]yarn global remove [package]
Run tests for the current packagenpm testyarn test
Check for outdated packagesnpm outdatedyarn outdated
Run a scriptnpm runyarn run
Manage local package cachenpm cache cleanyarn cache clean
Log in or outnpm login/logoutyarn login/logout
rebuild packagenpm rebuildyarn add --force
clear npm/yarb cachenpm cache cleanyarn cache clean [package]

CLI commands doc