Why you should switch from NPM to Yarn, the differences, and a comparison of commands (with a cheatsheet)
We've switched to Yarn because it was built in collaboration with Facebook, Google, and others. We're primarily using it for how much faster it is though. Yarn supports emojis, is extremely faster, has automatic shrinkwrapping (hence the
yarn.lock file), and much better security.
You can find out why a package is installed (and what's using it):
yarn why <package-name>
And even list outdated packages that you might want to upgrade:
You can see all of the differences here as well.
Moving on! When you start a fresh project, you'll typically run this command:
With Yarn, all you need to run is this command:
yarn.lock file will be created after you do this. Don't delete this file though, it tells Yarn exactly what version of each dependency is installed so you have consistent installs across machines.
When you want to add a package in npm, you would do this:
npm install <my-package> --save
With Yarn, all we need to do is:
yarn add <my-package>
There's no need for a
--save flag, it will automatically add the package to the
NOTE: This only applies to standard dependencies, if you need to save a package as a developer dependency, please keep reading.
With npm, if you want to save a package as a developer dependency, you would add the
--save-dev flag. With Yarn, you can do this like so:
yarn add <my-dev-package> --dev
With npm, if you want a package available globally on the system, you would run:
npm install -g <my-global-package>
There's other ways to run the same command, e.g.:
npm install <my-global-package> --global npm i -g <my-global-package>
But for the sake of this document, I'm assuming you either know the shorthand way of doing things, or already have a preferred method. Anyways, when it comes to Yarn, this is how you install a package globally:
yarn global add <my-global-package>
With npm, when you want to update all of the packages you run:
npm update --save
And actually, it's really rare to use the
--save flag here.
With Yarn, we just have to run: