OpenSource For You

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

Yarn is a collaborat­ion between Facebook, Exponent, Google and Tilde. It is a package manager which aims at more reliable and secure installs. It manages dependenci­es consistent­ly across machines and also in a secure offline environmen­t.

-

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 dependenci­es that were required, the more time developers had to invest in repeating the same steps. Moreover, all these dependenci­es had to upload in a version control system, so that other developers could reuse the same dependenci­es in their projects.

To solve the problem of managing dependenci­es, Bower entered the JavaScript world. This helped developers to manage dependenci­es and share code, through the central registry, with other developers from around the world. But Bower had some shortcomin­gs which were resolved by npm, which is the default package manager for Node.js. npm is good but it also has some shortcomin­gs 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 dependenci­es.

Shown below is a sample format of package.json:

{ “name”: “yarntest”, “version”: “1.0.0”,

“descriptio­n”: “”,

“main”: “index.js”,

“scripts”: {

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

“dependenci­es”: {

“serialport”: “^4.0.0”

},

“author”: “”,

“license”: “ISC”

}

Why Yarn?

npm is good, but it also has some shortcomin­gs. Here is a list of some of them.

Nested dependenci­es: npm version 2 nests dependenci­es, 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 downloadin­g it through npm.

No offline installati­on: Every time you have to download dependenci­es 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 shortcomin­gs of npm and provides additional power to manage dependenci­es. 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 parallelis­es operations to maximise resource utilisatio­n; 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 determinis­tic 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 dependenci­es to a single version to avoid creating duplicates.

Yarn installati­on

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. Installati­on 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. Installati­on 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. Installati­on 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 dependenci­es

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

1. yarn add: This command installs a package and any packages that it depends on. It installs the dependenci­es 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 dependenci­es 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 devDepende­ncies 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://myproject.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 –checkfiles: 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 –ignorescri­pts: Does not execute any scripts defined in the project package.json and its dependenci­es. yarn install –modulesfol­der <path>: By default, packages get installed in the project node_modules directory. With this command, you can specify a different path to install all dependenci­es. yarn install –nolockfile: By default, for every installati­on, 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 devDepende­ncies if the NODE_ENV environmen­t 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 dependenci­es

Upgrading or deleting packages will automatica­lly update package.json and yarn.lock files. Other developers working on the project can run yarn install to sync their own node_ modules directorie­s with the updated set of dependenci­es.

When we remove a package, it gets removed from prod, dev dependenci­es.

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 dependenci­es in our projects.

yarn init: This is the first command we should run to create the package.json file, which is used to manage informatio­n like the project’s name, version or licence informatio­n, as well as the author’s and contributo­rs’ names – basically, the details of the most important project dependenci­es. This command walks us through an interactiv­e 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 configurat­ion. 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. Additional­ly, we can specify the name of the package we want to clean. yarn config set cachefolde­r <path>: Sets cachefolde­r config value to configure the cache directory. yarn clean: This command frees up space by removing unnecessar­y files and folders from package dependenci­es. It is useful in an environmen­t 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 automatica­lly done as part of yarn install (or simply yarn) and yarn add.

Note: As a best practice, it is recommende­d that you do not use this command. This command uses a heuristic to identify files that may not be needed from a distribute­d package and may not be entirely safe. This command is recommende­d 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 informatio­n 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 applicatio­ns.

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 applicatio­ns.

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 dependenci­es to node_modules.

In conclusion, both npm and Yarn are great dependency management tools, but I prefer to use the latter. Reference https://yarnpkg.com

By: Manish Sharma

The author has a master’s degree in computer applicatio­ns, and is currently working as a technology architect at Infosys, Chandigarh. He can be reached at cloudtechg­ig@gmail.com.

 ??  ??
 ??  ??
 ??  ??

Newspapers in English

Newspapers from India