Install yarn on linux

Как установить Yarn на Ubuntu 20.04

Yarn — это менеджер пакетов JavaScript, совместимый с npm, который помогает автоматизировать процесс установки, обновления, настройки и удаления пакетов npm. Он кэширует каждый загружаемый пакет и ускоряет процесс установки за счет распараллеливания операций.

В этом руководстве мы объясним, как установить Yarn на Ubuntu 20.04. Мы также рассмотрим основные команды и параметры Yarn.

Установка Yarn на Ubuntu

Установить Yarn на Ubuntu довольно просто. Мы включим официальный репозиторий Yarn, импортируем GPG-ключ репозитория и установим пакет. Репозиторий постоянно поддерживается и предоставляет самую последнюю версию.

Импортируйте GPG-ключ репозитория и добавьте репозиторий Yarn APT в вашу систему, выполнив следующие команды:

После включения репозитория обновите список пакетов и установите Yarn.

Приведенная выше команда также установит Node.js. Если вы установили Node через nvm, пропустите установку Node.js с помощью:

После завершения проверьте установку, распечатав версию Yarn:

Результат будет выглядеть примерно так:

Версия, установленная в вашей системе, может отличаться от указанной выше.

Это оно! Вы успешно установили Yarn на свой компьютер с Ubuntu и можете начать его использовать.

Использование пряжи

Теперь, когда Yarn установлен в вашей системе Ubuntu, давайте рассмотрим некоторые из наиболее распространенных команд Yarn.

Создание нового проекта

Начните с создания каталога для вашего приложения и перейдите в него:

Чтобы создать новый проект, запустите yarn init :

Команда задаст вам несколько вопросов. Введите информацию в соответствии с запросом или примите значения по умолчанию:

После завершения сценарий создает базовый файл package.json содержащий предоставленную информацию. Вы можете открыть и отредактировать этот файл в любое время.

Добавление зависимости

Чтобы добавить пакет npm в зависимости проекта, используйте команду yarn add за которой следует имя пакета:

Приведенная выше команда yarn.lock файлы package.json и yarn.lock .

По умолчанию, когда указано только имя пакета, Yarn устанавливает последнюю версию. Чтобы установить определенную версию или тег, используйте следующий синтаксис:

Обновление зависимости

Чтобы обновить пакеты, используйте одну из следующих команд:

Если имя пакета не указано, команда обновит зависимости проекта до последней версии в соответствии с диапазоном версий, указанным в файле package.json. В противном случае обновляются только указанные пакеты.

Удаление зависимости

Используйте команду yarn remove за которой следует имя пакета, чтобы удалить зависимость:

Команда удалит пакет и обновит файлы проекта package.json и yarn.lock .

Установка всех зависимостей проекта

Чтобы установить все зависимости проекта, указанные в файле package.json , выполните:

Выводы

Мы показали вам, как установить Yarn на вашу машину с Ubuntu. Для получения дополнительной информации о Yarn посетите их страницу документации .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии ниже.

Источник

2 — Installation

Migrating from Yarn 1

We’ve been compiling helpful advice when porting over from Yarn 1 on the following Migration Guide. Give it a look and contribute to it if you see things that aren’t covered yet! Make sure to consult the PnP Compatibility Table and enable the node-modules plugin if required!

About global installs

Using a single package manager across your system has always been a problem. To be stable, installs need to be run with the same package manager version across environments, otherwise there’s a risk we introduce accidental breaking changes between versions — after all, that’s why the concept of lockfile was introduced in the first place! And with Yarn being in a sense your very first project dependency, it should make sense to «lock it» as well.

For this reason, Yarn 2 and later are meant to be managed on a by-project basis. Don’t worry, little will change! Just make sure to first install the global Yarn binary that we will use to spawn the local ones:

Once you’ve followed the instructions (running yarn —version from your home directory should yield something like 1.22.0 ), go to the next section to see how to actually enable Yarn 2 on your project.

You’ve probably remarked the global Yarn is from the «Classic» line (1.x). This is expected! One extra perk of this system is that projects configured for Yarn 1 will keep using it instead of suddenly having to migrate to the 2.x configuration format. We wouldn’t have had to do this if Yarn had been «project locked» from the beginning, but hindsight is 20/20 😉

  1. Install the Yarn global binary to its latest version:

«Berry» is the codename for all versions of Yarn from 2 onwards: 2.x, 3.x, etc. It’s also the name of our repository!

Updating to the latest versions

Читайте также:  Как устанавливать eclipse для windows

Should you later want to update Yarn to the latest version, just run:

Yarn will then download the most recent binary from our website, and install it in your projects. Don’t forget to run a new install to update your artifacts, and to commit the results!

Installing the latest build fresh from master

From time to time even the most recent releases aren’t enough, and you then will want to try out the very latest master to check if a bug has been fixed. This has become very simple with Yarn 2! Just run the following command:

Similarly, specific PRs can be installed using the —branch flag:

Источник

Installation

Install via npm

It is recommended to install Yarn through the npm package manager, which comes bundled with Node.js when you install it on your system.

Once you have npm installed you can run the following both to install and upgrade Yarn:

Alternatives

Alpine

On Alpine Linux (3.6+), you can install Yarn with apk.

Currently, there are no Alpine packages available for RC or nightly builds of Yarn. Please use the tarball:

Installation Script

One of the easiest ways to install Yarn on macOS and generic Unix environments is via our shell script. You can install Yarn by running the following code in your terminal:

The installation process includes verifying a GPG signature. View the source on GitHub

You can also specify a version by running the following code in your terminal:

See the releases for possible versions.

Manual Install via tarball

You can install Yarn by downloading a tarball and extracting it anywhere.

Before extracting Yarn, it is recommended that you verify the tarball using GPG:

Path Setup

If Yarn is not found in your PATH, follow these steps to add it and allow it to be run from anywhere.

Note: your profile may be in your .profile , .bash_profile , .bashrc , .zshrc , etc.

  1. Add this to your profile: export PATH=»$PATH:/opt/yarn-[version]/bin» (the path may vary depending on where you extracted Yarn to)
  2. In the terminal, log in and log out for the changes to take effect

To have access to Yarn’s executables globally, you will need to set up the PATH environment variable in your terminal. To do this, add export PATH=»$PATH:`yarn global bin`» to your profile, or if you use Fish shell, simply run the command set -U fish_user_paths (yarn global bin) $fish_user_paths

Arch Linux

On Arch Linux, Yarn can be installed through the official package manager.

Currently, there are no Arch packages available for RC or nightly builds of Yarn. Please use the tarball:

Installation Script

One of the easiest ways to install Yarn on macOS and generic Unix environments is via our shell script. You can install Yarn by running the following code in your terminal:

The installation process includes verifying a GPG signature. View the source on GitHub

You can also specify a version by running the following code in your terminal:

See the releases for possible versions.

Manual Install via tarball

You can install Yarn by downloading a tarball and extracting it anywhere.

Before extracting Yarn, it is recommended that you verify the tarball using GPG:

Path Setup

If Yarn is not found in your PATH, follow these steps to add it and allow it to be run from anywhere.

Note: your profile may be in your .profile , .bash_profile , .bashrc , .zshrc , etc.

  1. Add this to your profile: export PATH=»$PATH:/opt/yarn-[version]/bin» (the path may vary depending on where you extracted Yarn to)
  2. In the terminal, log in and log out for the changes to take effect

To have access to Yarn’s executables globally, you will need to set up the PATH environment variable in your terminal. To do this, add export PATH=»$PATH:`yarn global bin`» to your profile, or if you use Fish shell, simply run the command set -U fish_user_paths (yarn global bin) $fish_user_paths

CentOS / Fedora / RHEL

On CentOS, Fedora and RHEL, you can install Yarn via our RPM package repository.

If you do not already have Node.js installed, you should also configure the NodeSource repository:

Then you can simply:

Currently, there are no RPM packages available for RC or nightly builds of Yarn. Please use the tarball:

Installation Script

One of the easiest ways to install Yarn on macOS and generic Unix environments is via our shell script. You can install Yarn by running the following code in your terminal:

Читайте также:  Three curtains on one windows

The installation process includes verifying a GPG signature. View the source on GitHub

You can also specify a version by running the following code in your terminal:

See the releases for possible versions.

Manual Install via tarball

You can install Yarn by downloading a tarball and extracting it anywhere.

Before extracting Yarn, it is recommended that you verify the tarball using GPG:

Path Setup

If Yarn is not found in your PATH, follow these steps to add it and allow it to be run from anywhere.

Note: your profile may be in your .profile , .bash_profile , .bashrc , .zshrc , etc.

  1. Add this to your profile: export PATH=»$PATH:/opt/yarn-[version]/bin» (the path may vary depending on where you extracted Yarn to)
  2. In the terminal, log in and log out for the changes to take effect

To have access to Yarn’s executables globally, you will need to set up the PATH environment variable in your terminal. To do this, add export PATH=»$PATH:`yarn global bin`» to your profile, or if you use Fish shell, simply run the command set -U fish_user_paths (yarn global bin) $fish_user_paths

Debian / Ubuntu

On Debian or Ubuntu Linux, you can install Yarn via our Debian package repository. You will first need to configure the repository:

On Ubuntu 16.04 or below and Debian Stable, you will also need to configure the NodeSource repository to get a new enough version of Node.js.

Then you can simply:

Note: Ubuntu 17.04 comes with cmdtest installed by default. If you’re getting errors from installing yarn , you may want to run sudo apt remove cmdtest first. Refer to this for more information.

If using nvm you can avoid the node installation by doing:

Note: Due to the use of nodejs instead of node name in some distros, yarn might complain about node not being installed. A workaround for this is to add an alias in your .bashrc file, like so: alias node=nodejs . This will point yarn to whatever version of node you decide to use.

Path Setup

If Yarn is not found in your PATH, follow these steps to add it and allow it to be run from anywhere.

Note: your profile may be in your .profile , .bash_profile , .bashrc , .zshrc , etc.

  1. Add this to your profile: export PATH=»$PATH:/opt/yarn-[version]/bin» (the path may vary depending on where you extracted Yarn to)
  2. In the terminal, log in and log out for the changes to take effect

To have access to Yarn’s executables globally, you will need to set up the PATH environment variable in your terminal. To do this, add export PATH=»$PATH:`yarn global bin`» to your profile, or if you use Fish shell, simply run the command set -U fish_user_paths (yarn global bin) $fish_user_paths

Gentoo Linux

On Gentoo Linux, you can install Yarn with portage.

Currently, there are no Gentoo packages available for RC or nightly builds of Yarn. Please use the tarball:

Installation Script

One of the easiest ways to install Yarn on macOS and generic Unix environments is via our shell script. You can install Yarn by running the following code in your terminal:

Источник

Using Yarn on Ubuntu and Other Linux Distributions

Last updated April 10, 2020 By Abhishek Prakash 6 Comments

This quick tutorial shows you the official way of installing Yarn package manager on Ubuntu and Debian Linux. You’ll also learn some basic Yarn commands and the steps to remove Yarn completely.

Yarn is an open source JavaScript package manager developed by Facebook. It is an alternative or should I say improvement to the popular npm package manager. Facebook developers’ team created Yarn to overcome the shortcomings of npm . Facebook claims that Yarn is faster, reliable and more secure than npm .

Like npm, Yarn provides you a way to automate the process of installing, updating, configuring, and removing packages retrieved from a global registry.

The advantage of Yarn is that it is faster as it caches every package it downloads so it doesn’t need to download it again. It also parallelizes operations to maximize resource utilization. Yarn also uses checksums to verify the integrity of every installed package before its code is executed. Yarn also guarantees that an install that worked on one system will work exactly the same way on any other system.

If you are using nodejs on Ubuntu, probably you already have npm installed on your system. In that case, you can use npm to install Yarn globally in the following manner:

However, I would recommend using the official way to install Yarn on Ubuntu/Debian.

Installing Yarn on Ubuntu and Debian [The Official Way]

The instructions mentioned here should be applicable to all versions of Ubuntu such as Ubuntu 18.04, 16.04 etc. The same set of instructions are also valid for Debian and other Debian based distributions.

Читайте также:  Обновление центра обновления windows server 2012

Since the tutorial uses Curl to add the GPG key of Yarn project, make sure to install curl on Ubuntu first.

The above command will install Curl if it wasn’t installed already. Now that you have curl, you can use it to add the GPG key of Yarn project in the following fashion:

After that, add the repository to your sources list so that you can easily upgrade the Yarn package in future with the rest of the system updates:

You are set to go now. Update Ubuntu or Debian system to refresh the list of available packages and then install yarn:

This will install Yarn along with nodejs. Once the process completes, verify that Yarn has been installed successfully. You can do that by checking the Yarn version.

For me, it showed an output like this:

This means that I have Yarn version 1.12.3 installed on my system.

Using Yarn

I presume that you have some basic understandings of JavaScript programming and how dependencies work. I am not going to go in details here. I’ll show you some of the basic Yarn commands that will help you getting started with it.

Creating a new project with Yarn

Like npm , Yarn also works with a package.json file. This is where you add your dependencies. All the packages of the dependencies are cached in the node_modules directory in the root directory of your project.

In the root directory of your project, run the following command to generate a fresh package.json file:

It will ask you a number of questions. You can skip the questions r go with the defaults by pressing enter.

With this, you get a package.json file of this sort:

Now that you have the package.json, you can either manually edit it to add or remove package dependencies or use Yarn commands (preferred).

Adding dependencies with Yarn

You can add a dependency on a certain package in the following fashion:

For example, if you want to use Lodash in your project, you can add it using Yarn like this:

And you can see that this dependency has been added automatically in the package.json file:

By default, Yarn will add the latest version of a package in the dependency. If you want to use a specific version, you may specify it while adding.

As always, you can also update the package.json file manually.

Upgrading dependencies with Yarn

You can upgrade a particular dependency to its latest version with the following command:

It will see if the package in question has a newer version and will update it accordingly.

You can also change the version of an already added dependency in the following manner:

You can also upgrade all the dependencies of your project to their latest version with one single command:

It will check the versions of all the dependencies and will update them if there are any newer versions.

Removing dependencies with Yarn

You can remove a package from the dependencies of your project in this way:

Install all project dependencies

If you made any changes to the project.json file, you should run either

to install all the dependencies at once.

How to remove Yarn from Ubuntu or Debian

I’ll complete this tutorial by mentioning the steps to remove Yarn from your system if you used the above steps to install it. If you ever realized that you don’t need Yarn anymore, you will be able to remove it.

Use the following command to remove Yarn and its dependencies.

You should also remove the Yarn repository from the repository list:

The optional next step is to remove the GPG key you had added to the trusted keys. But for that, you need to know the key. You can get that using the apt-key command:

The key here is the last 8 characters of the GPG key’s fingerprint in the line starting with pub.

So, in my case, the key is 86E50310 and I’ll remove it using this command:

You’ll see an OK in the output and the GPG key of Yarn package will be removed from the list of GPG keys your system trusts.

I hope this tutorial helped you to install Yarn on Ubuntu, Debian, Linux Mint, elementary OS etc. I provided some basic Yarn commands to get you started along with complete steps to remove Yarn from your system.

I hope you liked this tutorial and if you have any questions or suggestions, please feel free to leave a comment below.

Like what you read? Please share it with others.

Источник

Оцените статью