啟用 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 對 幽靈相依性的保護。
用於引導 Rush 的 install-run-rush.js
幸運的是,有一個更優雅的解決方案可以在 CI 機器上安裝 Rush:所有 Rush 儲存庫都帶有一個腳本 common/scripts/install-run-rush.js
,它將會
- 尋找您的 rush.json 檔案
- 讀取其中指定的
rushVersion
- 使用您儲存庫的 .npmrc 檔案中的適當設定,自動將該版本的 Rush 安裝在 common/temp/install-run 資料夾下
- 使用您儲存庫的 .npmrc 檔案中的適當設定
- ...然後調用 Rush 工具,並傳遞您提供的任何命令列參數
安裝會被快取,因此這不會比正常調用 Rush 慢。 事實上,對於會保留先前執行檔案的 CI 系統,install-run-rush.js 比 npm 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 網站 QR 碼的指令::-)
~/my-repo$ node common/scripts/install-run.js qrcode@1.2.2 qrcode https://rush.dev.org.tw
請注意,install-run.js 命令列略有不同:它必須包含套件名稱和版本(可以是 SemVer 範圍,但最好避免不確定性)。 它還需要第二個參數,指定可執行二進位檔的名稱(即使二進位檔名稱通常與套件名稱相同)。 在上面的範例中,我們調用 qrcode
二進位檔,其命令列參數為 https://rush.dev.org.tw
。
當然,更直接的方法是將 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 建置管線的對等設定範例,請查看開發 Rush 的 monorepo 中的 build.yaml 檔案。