정보

Github Action으로 Gatsby 자동 배포하기

OneCrazyman 2024. 3. 9. 01:47

Gatsby 블로그를 시작하여 젤 처음 관문이였던 빌드된 public 폴더를 page로 빌드하기 위해 main 브랜치와 deploy용 브랜치를 따로 운영하여 배포를 진행하였다. 

 

기존 사용 예제

"scripts": {
    "deploy": "gatsby build --prefix-paths && gh-pages -d public -b deploy" //브랜치 네임이 "deploy" 일때, -b {브랜치명}
}
npm i gh-pages

 

기존의 deploy 방식

새로운 방식

하지만 기존 방식은 main 파일이 push 되지 않은채 새롭게 빌드된 정적 사이트 파일만 deploy용 브랜치를 통해 배포되었고,

이는 깃허브 main에서는 업데이트되지 않는 점과 포스팅시 커밋 메세지를 남기지 못하는 점이 걸려 Github Build and deployment에서 제공하는 Github Actions를 사용해보기로 하였다.

 

 

현재는 적용된 상태라 보이지 않는데 처음 설정시 레포의 설치된 환경에 따라 기본적인 Action 파일을 제공해주는거 같았다. 본인은 기본 제공해주는 gatsby.yml 파일을 사용하였다. 

 

# Sample workflow for building and deploying a Gatsby site to GitHub Pages
#
# To get started with Gatsby see: https://www.gatsbyjs.com/docs/quick-start/
#
name: Deploy Gatsby site to Pages

on:
  # Runs on pushes targeting the default branch
  push:
    branches: ["main"]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
  group: "pages"
  cancel-in-progress: false

# Default to bash
defaults:
  run:
    shell: bash

jobs:
  # Build job
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Detect package manager
        id: detect-package-manager
        run: |
        	#사용자의 환경에 따라 manager를 타게팅해줌 필자는 자동으로 npm으로 설정됨
          if [ -f "${{ github.workspace }}/yarn.lock" ]; then
            echo "manager=yarn" >> $GITHUB_OUTPUT
            echo "command=install" >> $GITHUB_OUTPUT
            exit 0
          elif [ -f "${{ github.workspace }}/package.json" ]; then
            echo "manager=npm" >> $GITHUB_OUTPUT
            echo "command=ci" >> $GITHUB_OUTPUT
            exit 0
          else
            echo "Unable to determine package manager"
            exit 1
          fi
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: ${{ steps.detect-package-manager.outputs.manager }}
      - name: Setup Pages
        id: pages
        uses: actions/configure-pages@v4
        with:
          # Automatically inject pathPrefix in your Gatsby configuration file.
          #
          # You may remove this line if you want to manage the configuration yourself.
          static_site_generator: gatsby
      - name: Restore cache
        uses: actions/cache@v4
        with:
          path: |
            public
            .cache
          key: ${{ runner.os }}-gatsby-build-${{ hashFiles('public') }}
          restore-keys: |
            ${{ runner.os }}-gatsby-build-
      - name: Install dependencies
        run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }}
      - name: Build with Gatsby
        env:
          PREFIX_PATHS: 'true'
          PATH_PREFIX: '/TIL' #수정/추가 사항
        run: ${{ steps.detect-package-manager.outputs.manager }} run build
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./public

  # Deployment job
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

 

preflix 옵션만 추가해 수정해주었다. 해당 코드를 사용하기전에 git token을 발급받고 secrets에 등록하여 권한을 얻는등 여러가지를 시도해보았지만, 위의 개츠비에서 예제로 준 코드가 직빵으로 잘 작동하였다.

이후 main에 push하게되면 yml의 작동 조건인 on: push 에 걸려 자동으로 build 되고 deploy 되는 모습을 볼 수 있다.

 

이제 포스팅시 커밋메세지와 전체 파일에 대한 업데이트는 물론 깃헙 잔디❔ 까지 심을 수 있게되었다.