Rush Stack商店博客活动
跳至主要内容

启用 CI 构建

当您为持续集成设置 PR 构建定义时,自动化脚本可以运行开发人员手动调用的基本相同命令。但是,您可能会发现一些额外的选项很有用。

如果我们手动调用这些命令,它可能看起来像这样

# Fetch the main branch
git fetch origin main:refs/remotes/origin/main -a

# (optional) Fail if the developer didn't create a required change log.
# By "fail", we mean that the script will stop because Rush returned
# a nonzero exit code.
rush change -v

# Install NPM packages in the common folder, but don't automatically do "rush link"
rush install --no-link

# Run "rush link" explicitly, so your CI system can measure it as a separate step
rush link

# Do a full "ship" build, showing detailed logs in real time
# (We assume "--ship" was defined in common/config/rush/command-line.json)
rush rebuild --ship --verbose

但有一个问题——如果您的 CI 环境没有预安装 Rush 怎么办?您可能考虑在仓库的根目录下添加一个 package.json,然后调用 npm install 来安装 Rush。不幸的是,这将引入一个幽灵 node_modules 文件夹,这将破坏 Rush 对 幽灵依赖项 的保护。

install-run-rush.js 用于引导 Rush

幸运的是,有一个更优雅的解决方案可以在 CI 机器上安装 Rush:所有 Rush 仓库都带有一个脚本 common/scripts/install-run-rush.js,它将

  • 找到您的 rush.json 文件
  • 读取其中指定的 rushVersion
  • common/temp/install-run 文件夹下自动安装该版本的 Rush
  • 使用来自您仓库的 .npmrc 文件的适当设置
  • ...然后调用 Rush 工具,并传递您提供的任何命令行参数

安装是缓存的,因此这并不比通常调用 Rush 慢。实际上,对于保留先前运行文件的 CI 系统,install-run-rush.jsnpm install 更快,因为它可以根据正在构建的 Git 分支缓存 Rush 的不同版本。

尝试从您的 shell 执行脚本

~$ cd my-repo
~/my-repo$ node common/scripts/install-run-rush.js --help
~/my-repo$ node common/scripts/install-run-rush.js install

下面我们将展示如何将其纳入 Travis 构建定义。

install-run.js 用于其他命令

顺便说一句,Rush 提供了第二个脚本 install-run.js,它允许您将此相同技术用于任意 NPM 包。例如,以下命令打印 Rush 网站的二维码: :-)

~/my-repo$ node common/scripts/install-run.js qrcode@1.2.2 qrcode https://rush.node.org.cn

请注意,install-run.js 命令行略有不同:它必须包含包名称和版本(可以是 SemVer 范围,尽管最好避免不确定性)。它还需要第二个参数来指定可执行二进制文件的名(即使二进制文件名通常与包名相同)。在上面的示例中,我们调用了 qrcode 二进制文件,它的命令行参数是 https://rush.node.org.cn

当然,更直接的方法是将 qrcode 指定为某个 package.json 文件的普通依赖项,例如 tools/repo-scripts 项目。这样它就可以成为您正常安装的一部分,并由您仓库的 shrinkwrap 文件跟踪。但在某些情况下这是不可取的,例如仅由不需要 rush install 的轻量级 CI 作业使用的脚本,或者即使 rush install 状态损坏或过时也需要正常工作的 Git 钩子。

来自 "rush init" 的 GitHub Actions 示例

GitHub Actions 是一种持续集成构建服务,它与 GitHub 集成,并对开源项目免费。rush init 命令创建一个 ci.yml 管道,如果您使用此服务,这是一个很好的起点。注意它如何使用 install-run-rush.js 来调用 Rush 工具

.github/workflows/ci.yml

name: CI
on:
push:
branches: ['main']
pull_request:
branches: ['main']
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 2
- name: Git config user
uses: snow-actions/git-config-user@v1.0.0
with:
name: # Service Account's Name
email: # Service Account's Email Address
- uses: actions/setup-node@v3
with:
node-version: 16
- name: Verify Change Logs
run: node common/scripts/install-run-rush.js change --verify
- name: Rush Install
run: node common/scripts/install-run-rush.js install
- name: Rush rebuild
run: node common/scripts/install-run-rush.js rebuild --verbose --production

有关使用 Azure DevOps 构建管道进行等效设置的示例,请查看 build.yaml 文件,位于开发 Rush 的单体仓库中。