如何在 Ubuntu 22.04 上安装 Yarn 包管理器
本教程适用于这些操作系统版本
- Ubuntu 22.04(Jammy Jellyfish)
- Ubuntu 20.04(Focal Fossa)
在此页
- 先决条件
- 安装 Node.js
- 启用核心包
- 在 Ubuntu 22.04 上安装 Yarn
- 如何使用 Yarn
- 如何升级 Yarn
- 移除纱线包
- 结论
Yarn 是 JavaScript 环境的包管理器。它是 NPM 包管理器的替代品,由 Facebook 与 Google、Tilde 和 Expo Dev 合作开发。 Yarn 加快了从本地缓存安装包的安装过程。它旨在解决大型代码库的安全和性能相关问题。
在本教程中,我将向您展示如何在 Ubuntu 22.04 上安装 Yarn 包管理器。
先决条件
- 一台运行 Ubuntu 22.04 的服务器。
- 在服务器上配置了根密码。
安装 Node.js
在安装 Yarn 之前,必须在您的服务器上安装 Node.js 包。首先,使用以下命令安装 curl 工具:
apt install curl -y
接下来,使用以下命令添加 Node.js 存储库:
curl -fsSL https://deb.nodesource.com/setup_current.x | bash -
接下来,使用以下命令安装 Node.js 包:
apt install nodejs -y
启用核心包
Corepack 是一个包管理器,允许您在服务器上安装 Yarn。默认情况下,Corepack 随 Node.js 包一起安装。但默认情况下它是禁用的。所以你需要启用它才能使用。
您可以使用以下命令启用 Corepack:
corepack enable
在 Ubuntu 22.04 上安装 Yarn
使用 Corepack,您可以轻松地在您的服务器上安装和激活 Yarn 包。 Corepack 允许您跨多个项目管理不同的 Yarn 包版本。
运行以下命令安装并激活最新的 Yarn 版本:
corepack prepare --activate
您现在可以使用以下命令检查 Yarn 版本:
yarn --version
您将获得以下输出:
3.2.3
您还可以使用 Corepack 安装旧版本的 Yarn。
例如,运行以下命令安装 Yarn 3.1.1:
corepack prepare --activate
接下来,将默认版本设置为 Yarn 3.1.1,并运行以下命令:
yarn set version 3.1.1
您将获得以下输出:
? YN0000: Retrieving https://repo.yarnpkg.com/3.1.1/packages/yarnpkg-cli/bin/yarn.js
? YN0000: Saving the new release in .yarn/releases/yarn-3.1.1.cjs
? YN0000: Done in 0s 790ms
如果要将默认的 Yarn 版本设置为稳定版本,请运行以下命令:
yarn set version stable
如何使用纱线
使用 Yarn,您可以轻松地安装和删除任何包。
首先,使用以下命令初始化 Yarn 项目:
yarn init
您将获得以下输出:
{
name: 'root',
packageManager: ''
}
接下来,使用以下命令安装 React 包:
yarn add react
您将获得以下输出:
? YN0000: ? Resolution step
? YN0000: ? Completed in 0s 332ms
? YN0000: ? Fetch step
? YN0013: ? :4.0.0 can't be found in the cache and will be fetched from the remote registry
? YN0013: ? :1.4.0 can't be found in the cache and will be fetched from the remote registry
? YN0013: ? :18.2.0 can't be found in the cache and will be fetched from the remote registry
? YN0000: ? Completed in 0s 418ms
? YN0000: ? Link step
? YN0000: ? Completed
? YN0000: Done in 0s 808ms
要安装特定版本的包,请运行以下命令:
yarn add
要升级依赖项,请运行以下命令:
yarn up package
要删除任何包,请运行以下命令:
yarn remove package
如何升级 Yarn
如果要将 Yarn 升级到最新版本,请运行以下命令:
yarn set version stable
yarn install
移除纱包
如果你不想使用 Yarn,那么你可以使用以下命令轻松卸载它:
corepack disable yarn
结论
在这篇文章中,我们解释了如何在 Ubuntu 22.04 上安装 Yarn。我们还解释了如何安装和管理多个 Yarn 版本。我希望本指南能帮助您管理您的 JavaScript 项目。