AWS Amplify로 React 배포하기
🍾

AWS Amplify로 React 배포하기

Created
2022/05/21
Tags
AWS
Amplify
React
Deploy
 
 
2022-05-21 @이영훈
 
 
Amplify로 React를 배포하는 방법을 기록으로 남깁니다.
  • 브랜치 별로 다른 build 커맨드를 적용합니다.
  • multi-level subdomain (XX.YY.leedo.me)을 적용할 것입니다.
 
Amplify는 내부적으로 S3와 Cloudfront를 사용합니다. CodeBuild로 CI 후에 S3에 파일(artifacts)을 저장하고 Cloudfront 캐시를 invalidate 해야했는데 그 과정을 자동으로 해줘서 편리하게 배포할 수 있어서 좋습니다.
 
 

Amplify로 React 배포하기

 
notion image
 
Github으로 진행하겠습니다. 상황에 맞는 것을 선택해주세요.
notion image
 
Repository와 Branch를 선택합니다
notion image
 
App 이름을 기입합니다. Build command는 환경을 찾아서 자동으로 만들어줍니다.
yarn을 확인해서 yarn build 커맨드를 만들어주었습니다.
notion image
 
설정이 맞으면 Save and deploy를 눌러줍니다
notion image
 
이렇게 배포가 끝났습니다. 정말 빠르게 배포할 수 있어 좋습니다.
 

다른 branch 연결하기

 
General에서 Branches에서 다른 브랜치를 연결할 수 있습니다.
notion image
 
연결할 브랜치를 선택합니다. 저는 main 브랜치를 선택했습니다.
notion image
 
설정이 맞으면 Save and deploy를 눌러서 브랜치를 연결합니다.
notion image
 
 

브랜치 별로 build 커맨드 다르게 적용

 
package.json 파일이 다음과 같이 환경별로 다르게 빌드를 해야하는 상황이 있습니다.
branch 별로 환경변수를 다르게 사용하는 경우입니다.
YAML
// package.json

"scripts": {
  "build:local": "env-cmd -f .env.local react-scripts build",
  "build:dev": "env-cmd -f .env.dev react-scripts build",
  "build:stage": "env-cmd -f .env.stage react-scripts build",
  "build:prod": "env-cmd -f .env.prod react-scripts build"
},
 
이때는 amplify 환경변수 설정으로 branch 별로 다른 커맨드를 실행하면 됩니다.
(전체 코드는 밑에서 확인할 수 있습니다.)
YAML
build:
  commands:
    - yarn run build:$BUILD_ENV
 
Environment variables 설정에 들어갑니다.
notion image
 
그리고 브랜치 별로 환경을 나타내는 환경변수 명(BUILD_ENV)을 정의하고, 값도 적어줍니다
다음과 같이 정의하였습니다
notion image
 
그리고 amplify.yml 파일을 수정합니다.
왼쪽의 Build setting에 들어갑니다 그리고 Edit 버튼을 누릅니다
notion image
 
다음과 같이 yarn run build → yarn run build:$BUILD_ENV 로 수정합니다
YAML
version: 1
frontend:
  phases:
    preBuild:
      commands:
        - yarn install
    build:
      commands:
        - yarn run build:$BUILD_ENV
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
 
빌드를 해보면 커맨드가 반영되었음을 알 수 있습니다.
notion image
 
 

도메인 적용하기: multi-level subdomain

도메인을 적용합니다. 개발환경 별로 서브 도메인을 적용해야하기 때문에 multi-level subdomain을 적용했습니다.
 
Domain management에 들어가서 도메인을 추가 버튼을 누릅니다.
notion image
 
다음과 같이 main 브랜치는 root 도메인을 사용하고 dev, stage를 붙이는 방식으로 설정을 했습니다.
notion image
 
 
 

Ref.