iT邦幫忙

2025 iThome 鐵人賽

DAY 28
0

為什麼要做 CI/CD?

CI/CD(Continuous Integration / Continuous Deployment)是一套自動化流程,主要目的:

  • 持續整合 (CI):每次 commit / PR 自動建置、測試,確保程式碼健康
  • 持續部署 (CD):測試通過後,自動部署到測試或正式環境,降低手動操作錯誤

好處:

  1. 減少手動部署出錯
  2. 快速回饋測試結果
  3. 團隊協作更順暢

簡單講,CI/CD 就像「每次你寫完程式碼,它自動幫你檢查、打包、發佈」。


CI/CD 的流程示意

Git Push / PR
       ↓
  CI: Build + Test
       ↓
  CD: Deploy (Firebase Hosting / Backend)

對於 React + Firebase 專案,常見流程:

  1. 前端
    • build React 專案
    • run lint + unit test + e2e test
    • deploy 到 Firebase Hosting
  2. 後端 / Functions
    • build / bundle
    • run unit test
    • deploy 到 Firebase Functions 或自己的 Express 服務

CI/CD 工具選擇

常見工具:

工具 適合場景
GitHub Actions Github 專案,整合 GitHub Repository 最簡單
GitLab CI GitLab 專案,自動化流程彈性大
Bitbucket Pipelines Bitbucket 專案
Jenkins / CircleCI / Travis CI 跨平台、彈性高,適合大型專案

這裡以 GitHub Actions 做範例示範,方便整合 Firebase Hosting + Functions。


GitHub Actions 範例

  1. 建立 workflow 檔案
  2. 在專案 .github/workflows 下新增 ci-cd.yml
name: CI/CD React + Firebase

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
      # 1. 取得程式碼
      - name: Checkout repo
        uses: actions/checkout@v3

      # 2. Node.js 環境
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 18

      # 3. 安裝套件
      - name: Install dependencies
        run: npm ci

      # 4. 執行 lint
      - name: Run ESLint
        run: npm run lint

      # 5. 執行測試
      - name: Run tests
        run: npm test

      # 6. Build React
      - name: Build React App
        run: npm run build

      # 7. Deploy Firebase
      - name: Deploy to Firebase
        uses: w9jds/firebase-action@v2.2.0
        with:
          args: deploy --only hosting,functions
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
  • FIREBASE_TOKEN:必須先在本地用 firebase login:ci 取得 token,再設定到 GitHub Secrets
  • deploy --only hosting,functions:可以指定要部署 Firebase Hosting、Functions 或其他服務
  • 每次 push 到 main branch 就會觸發自動部署
  • 先 lint + test 可以確保程式碼品質

上一篇
進階版 MFA 實作:Email / Google 登入 + SMS 二階段驗證
下一篇
CI/CD 實作 — React + Firebase(Preview → Staging → Production)
系列文
不只是登入畫面!一起打造現代化登入系統29
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言