在 CircleCI 對 Monorepo 一部分 sub-folder 做 CI/CD 的範例
先給程式碼範例。
- https://github.com/sunpochin/nodejs-video-api/blob/main/.circleci/config.yml
這個 Monorepo 的根目錄有一個 frontend 跟 backend folder.
而 config.yml 定義了build-frontend 跟 unit-test-backend 兩個工作,在每一個 run 的步驟先 cd backend 然後做 yarn test:unit 等等工作。
# Use the latest 2.1 version of CircleCI pipeline process engine.
# See: https://circleci.com/docs/configuration-reference
version: 2.1
orbs:
node: circleci/node@4.1.0
jobs:
build-frontend:
docker:
- image: cimg/node:19.8.1
executor: node/default
steps:
- checkout
- node/install-packages:
pkg-manager: yarn
app-dir: frontend
- run:
name: Install dependencies
command: |
cd frontend
yarn install
- run:
name: Build frontend
command: |
cd frontend
yarn build
- store_artifacts:
path: |
frontend/build
destination: builds
unit-test-backend:
docker:
- image: cimg/node:19.8.1
executor: node/default
steps:
- checkout
- node/install-packages:
pkg-manager: npm
app-dir: backend
# - restore_cache:
# key: dependency-cache-{{ checksum "backend/package-lock.json" }}
- run:
name: Install dependencies
command: |
cd backend
yarn
- run:
name: Run test for the application
command: |
cd backend
yarn test:unit
- run:
name: Send coverage data to Coveralls
command: |
cd backend
yarn coverage
# - save_cache:
# key: dependency-cache-{{ checksum "backend/package-lock.json" }}
# paths:
# - ./backend/node_modules
- store_artifacts:
path: |
backend/build
destination: builds
workflows:
version: 2
build:
jobs:
- unit-test-backend:
filters:
branches:
only: main
# - build-frontend:
# filters:
# branches:
# only: main
- 這段的 app-dir: backend 我不確定是否需要,等下我拿掉試試看。
- node/install-packages:
pkg-manager: yarn
app-dir: frontend
yarn coverage: 用來顯示 jest --coverage 的結果。
上 coveralls 開通帳號,引入 github repos, 把要顯示的 github repo 打開。
那一頁會顯示 YOUR COVERALLS REPO TOKEN, 這要填入 CircleCI 的 project variables.
然後在 CircleCI 下次正確執行後,它會把 coverage 結果傳給 coveralls, 就有個網頁可以顯示: https://coveralls.io/github/sunpochin/nodejs-video-api 還可以把 badge 貼到 github 首頁。
我參考了這幾篇但沒有看懂,本來想放棄 CircleCI 改用 Github Action 或 Travis CI, 但因為 CircleCI 對 open source project 是免費....後來問 chatGPT 得到回答,修改一部分符合我的需求。
https://discuss.circleci.com/t/how-to-working-directory-when-using-monorepo/44875
https://discuss.circleci.com/t/circleci-best-practices-in-path-based-builds-monorepo-strategy/40238
https://hackernoon.com/continuous-integration-for-a-monorepo-on-circleci-example