Why yarn was developed when there was already npm?
Yarn was built by Facebook to solve major problems they faced with npm, such as slower installation of packages and there were also a few security issues in npm.
How Installation of packages takes place?
When a package is installed, it carries out a set of tasks.
In npm, when installing multiple packages, it waits for a package to be fully installed before moving to another package. i.e., the tasks are executed per package sequentially.
Yarn installs tasks in parallel, thus increasing performance and speed.
To test this,
react using npm and Yarn. The timings were:
- npm — 3.572 seconds
- Yarn — 1.44 seconds
Lock file generation
Both npm and yarn keep track of the project’s dependencies and their version numbers in the
package.json file. Whenever you install dependencies, you may notice that the dependency’s version may start with
^ before the version number. This means that whenever we install all the packages in another machine or manually run the command to install, the package manager looks for newer versions released. If there is a newer version then that is automatically installed rather than the one mentioned in the package file.
There are two ways to avoid this if you don’t want automatic change in your packages, one is to generate a lock file so that only a particular version is installed every single time and the other is to remove
^ in the package file.
Yarn automatically adds a
yarn.lock file when dependencies are added. In npm,
npm shrinkwrap command generates a lock file as well. But, the difference is that Yarn always creates and updates the
yarn.lock file, while npm does not create the lock file by default. It only updates if a
npm-shrinkwrap.json exists. npm v5.0 comes with a new package named lock.json file and has sincerely discarded the npm-shrinkwrap system. This has efficiently enhanced the installation process and performance even though it has not yet reached the speed levels of Yarn.
Npm automatically executes a code that allows the other packages to get included in the fly, thus resulting in several vulnerabilities in the security system. On the other hand, Yarn installs those files which are only from the yarn.lock or package.json files. Therefore it is considered more secured than npm packages.
Both of them have two different sets of benefits and features which help the users in different ways possible. Yarn is more efficient when compared to npm. However, Yarn is also responsible for taking up a lot of hard disk space. Yarn is a newer package and people are much skeptical about Yarn over npm since it’s much older, but Yarn is becoming popular these days with better stability and security updates. It also has to be noted that npm is also trying to catch up with other package managers, as developers are working on it.