Yarn: A Quick, Reliable and Safe Way to Share Code

0
7157

Yarn is a collaboration between Facebook, Exponent, Google and Tilde. It is a package manager which aims at more reliable and secure installs. It manages dependencies consistently across machines and also in a secure offline environment.

Earlier, developers typically looked for the package (JS, CSS) on the Internet, downloaded the zipped version, extracted it and linked it to the Web page. But the first four steps were very time consuming. The more dependencies that were required, the more time developers had to invest in repeating the same steps. Moreover, all these dependencies had to upload in a version control system, so that other developers could reuse the same dependencies in their projects.

To solve the problem of managing dependencies, Bower entered the JavaScript world. This helped developers to manage dependencies and share code, through the central registry, with other developers from around the world. But Bower had some shortcomings which were resolved by npm, which is the default package manager for Node.js. npm is good but it also has some shortcomings that have now been resolved by Yarn.

Yarn

Yarn is a package manager for your code. It allows you to use and share code with other developers from around the world through a central registry and in other ways. Yarn does this quickly, securely, and reliably so you don’t ever have to worry. Yarn is fast, reliable and offers secure dependency management.

Code is shared through something called a package/module. A package contains all the code being shared as well as a package.json file, which describes the package and dependencies.

Shown below is a sample format of package.json:

{

“name”: “yarntest”,

“version”: “1.0.0”,

“description”: “”,

“main”: “index.js”,

“scripts”: {

“test”: “echo \”Error: no test specified\” && exit 1”

},

“dependencies”: {

“serialport”: “^4.0.0”

},

“author”: “”,

“license”: “ISC”

}

Why Yarn?

npm is good, but it also has some shortcomings. Here is a list of some of them.

  • Nested dependencies: npm version 2 nests dependencies, which leads to duplicates. For users of Windows, file paths may get long, which causes problems with Windows when trying to delete them. To fix this problem, you should use npm version 3.
  • Queued install: It installs each dependency one after the other, which may take up a lot of time.
  • Single registry: If a package is not on the npm registry, then forget about downloading it through npm.
  • No offline installation: Every time you have to download dependencies from the npm registry, a working Internet connection is required, which takes up a lot of time and consumes more bandwidth. Yarn overcomes most of the shortcomings of npm and provides additional power to manage dependencies. Here are the powerful features that Yarn offers.
  • Ultra-fast: It caches every package it downloads, so it never needs to download it again. It also parallelises operations to maximise resource utilisation; so install times are faster than ever.
  • Offline mode: If you’ve installed a package before, you can install it again without any Internet connection.
  • Extremely secure: Yarn uses checksums to verify the integrity of every installed package before its code is executed.
  • Super reliable: Using a detailed, but concise, lockfile format, and a deterministic algorithm for installs, Yarn is able to guarantee that an install that worked on one system will work exactly the same way on any other system.
  • Same packages: You can install any package from npm and keep your package workflow the same.
  • Network resilience: A single request failing will not cause an install to fail. Requests are retried upon failure.
  • Flat mode: You can resolve mismatched versions of dependencies to a single version to avoid creating duplicates.

Yarn installation

Before using Yarn, you’ll first need to install it on your system. There is an increasing number of ways to install Yarn. But in this article, I will cover only some of the options.

1. Installation on Windows: This is done through the installer .msi file. Download it using the link https://yarnpkg.com/latest.msi

Install via Chocolatey (package manager for Windows):

choco install yarn

Install via Scoop (command-line installer for Windows):

scoop install yarn

2. Installation on Centos, Fedora and RHEL Linux: Install it via the RPM package repository.

Step 1:

sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo

Step 2:

sudo yum install yarn

3. Installation on MacOS: Install Yarn through the Homebrew package manager. This will also install

Node.js if it is not already installed.

brew install yarn

Once Yarn is installed, then by using the command given below, we can check what version it is:

yarn --version

As of now, Yarn’s current stable version is v0.27.5 and the latest unstable version is v.28.4 (Nightly Build – this release may have bugs).

Installing project dependencies

Here is a list of possible Yarn commands that help us to add and install project dependencies.

1. yarn add: This command installs a package and any packages that it depends on. It installs the dependencies in the local node_modules directory and also an entry in the package.json and yarn.lock files. So members of a team working on the same project can get the same modules installed on their machines by executing the yarn or yarn install commands.

2. yarn install: This is used to install all dependencies for a project listed within package.json in the node_modules folder. It is most commonly used when you have just checked out code for a project, or when another developer on the project has added a new dependency that you need to pick up.

Some yarn add commands

yarn add <package …> [–exact/-E]: Using –exact or -E installs the exact version of the package. The default is to use the most recent release with the same major version.

yarn add <package …> [–tilde/-T]: Using –tilde or -T installs the most recent release of the packages that have the same minor version. The default is to use the most recent release with the same major version. For example, yarn add debug@1.2.3 –tilde would accept 1.2.9 but not 1.3.0.

  • yarn add package-name@tag: This command is used to install a package of a specified tag, e.g., beta, next or latest.
  • yarn add <package…> [–dev/-D]: Using –dev or -D will install one or more packages in devDependencies in package.json.

By default, all these packages get installed from the npm registry, but we can specify a local folder path, URL, gzip tarball local file path, Git repository URL, etc. A few examples are given below.

  • yarn add package-name: Installs the package from the npm registry unless we specify another one in package.json.
  • yarn add <file:/local/local/folder>: Installs a package that is on your local file system. This is useful to test out other packages of yours that haven’t been published to the public/ private registry yet.
  • yarn add <file:/local/foder/tarball.tgz>: Installs a package from a gzipped tarball, which could be used to share a package before publishing it.
  • yarn add <git remote url>: Installs a package from a remote Git repository.
  • yarn add <git remote url>#<branch/commit/tag>: Installs a package from a remote Git repository at a specific Git branch, Git commit or Git tag.
  • yarn add <https://my-project.org/package.tgz>: Installs a package from a remote gzipped tarball.

In case you are using npm, you would use –save or –save-dev. In Yarn, these have been replaced by yarn add and yarn add –dev.

Some yarn install commands

  • yarn install –check-files: Verifies that files already installed in node_modules are not removed.
  • yarn install –force: Re-fetches all the packages, even ones that were previously installed.
  • yarn install –ignore-scripts: Does not execute any scripts defined in the project package.json and its dependencies.
  • yarn install –modules-folder <path>: By default, packages get installed in the project node_modules directory. With this command, you can specify a different path to install all dependencies.
  • yarn install –no-lockfile: By default, for every installation, Yarn makes an entry in the yarn.lock file. This command instructs Yarn to neither read nor generate a yarn.lock lockfile.
  • yarn install –production[true|false]: Yarn will not install any package listed in devDependencies if the NODE_ENV environment variable is set to production. Use this flag to instruct Yarn to ignore NODE_ENV, and to take its production-or-not status instead.
  • yarn install –offline: Runs yarn install in offline mode.

Managing dependencies

Upgrading or deleting packages will automatically update package.json and yarn.lock files. Other developers working on the project can run yarn install to sync their own node_modules directories with the updated set of dependencies.

When we remove a package, it gets removed from prod, dev dependencies.

yarn remove [package-name]

ex: yarn remove mongoose

Packages can also be upgraded to the latest or a lower version.

yarn upgrade [package]

yarn upgrade [package]@[version]

yarn upgrade [package]@[tag]

Other useful Yarn commands

Yarn provides rich sets of commands, but I will explain only some of them.

After installing Node.js and Yarn, we can start using the Yarn commands to manage dependencies in our projects.

yarn init: This is the first command we should run to create the package.json file, which is used to manage information like the project’s name, version or licence information, as well as the author’s and contributors’ names – basically, the details of the most important project dependencies. This command walks us through an interactive session to create a package.json file.

yarn config commands: Here is a list of a few of these.

  • yarn config list: Displays the current configuration.
  • yarn config set <key> <value> [-g| –global]: Sets the config key to a certain value.
  • yarn config get <key>: Echoes the value for a given key to stdout.
  • yarn config delete <key>: Deletes a given key from the config.

yarn cache commands: These list, clean and change the cache directory.

  • yarn cache ls: Yarn stores every package in a global cache in your user directory on the file system. This command will print out every cached package.
  • yarn cache dir: This command will print out the path where Yarn’s global cache is currently stored.
  • yarn cache clean: This will clear the global cache. It will be populated again the next time yarn or yarn install is run. Additionally, we can specify the name of the package we want to clean.
  • yarn config set cache-folder <path>: Sets cache-folder config value to configure the cache directory.

yarn clean: This command frees up space by removing unnecessary files and folders from package dependencies. It is useful in an environment where packages are checked into the version control directly.

On command execution, Yarn will create a .yarnclean file that should be added to version control. Cleaning is then automatically done as part of yarn install (or simply yarn) and yarn add.

Note: As a best practice, it is recommended that you do not use this command. This command uses a heuristic to identify files that may not be needed from a distributed package and may not be entirely safe. This command is recommended only if you experience issues with the number of files that are installed as part of node_modules.

yarn info <package> [field]: This command will fetch information about a package and return it in a tree format. The package need not have been installed locally.

Example: yarn info express or yarn info express express@1.15.0.

Note that, by default, yarn info will not return the readme field (since it is often very long). To explicitly request that field, use yarn info react readme.

Yarn commands for managing package owners: Developers can write their own package and publish it either in a private or public registry. A package ‘owner’ in the registry is a user who has access to make changes to a package. A single package can have as many owners as you want.

Owners have permission to do the following tasks:

1. Publish new versions of the package

2. Add or remove other owners of the package

3. Change the metadata for a package

The following table lists a few yarn owner commands and their applications.

yarn owner ls <package> Lists all of the owners of a <package>.
yarn owner add <user> <package> Adds the <user> as an owner of the <package>. You must already be an owner of the <package> in order to run this command
yarn owner rm <user> <package>  Removes the <user> as an owner of the <package>. You must already be an owner of the <package> in order to run this command.

 

Commands for publishing a package to the npm registry: Once a package is published, you can never modify that specific version, so take care before publishing it.

The following table lists a few yarn publish commands and their applications.

yarn publish Publishes the package defined by the package.json in the current directory.
yarn publish [folder] Publishes the package contained in the specified folder. Project package.json should specify the package details.
yarn publish –access <public|restricted>

 The –access flag controls whether the npm registry publishes this package as a public package, or is restricted.

Yarn publish –new-version <version>  Skips the prompt for the new version by using the value of version instead.

Command for running a defined package script in package.json: Define a scripts objects in your package.json file like the one I have defined in the code given below:

{

“name”: “my-package-name”,

“scripts”: {

“build”: “babelsrc-dlib”,

“test”: “test-code”

}

}

Here, executing the command yarn run test on console will execute the script named ‘test-code’ defined in your package.json.

Yarn is highly compatible with npm. Projects built using Yarn can still be installed via npm, and vice versa. I have been using it for a long time and till now have not found any problems with it. The Yarn project is backed by companies like Google and Facebook; so I believe it will be developed actively.

Yarn is not supposed to replace npm; rather, it provides an improved set of features. It uses the same package.json file and saves dependencies to node_modules.

In conclusion, both npm and Yarn are great dependency management tools, but I prefer to use the latter.

LEAVE A REPLY

Please enter your comment!
Please enter your name here