[Git] Github Pages로 리액트 호스팅

김현수·2022년 12월 28일
0

Github Pages란?
GitHub를 이용해 웹 사이트를 무료로 호스팅해주는 서비스
GitHub 저장소에 프로젝트를 그대로 올리는것이 아닌, 프로젝트 build 결과물을 업로드하여 GitHub가 그 결과물을 호스팅하는 원리

1. GitHub에 저장소 생성

참고 깃허브 - 1번부터

2. Github와 로컬 프로젝트 연결하기

참고 깃 - 7번부터
git remote add origin https://github.com/(GitHub ID)/(Repository name).git
git push -u origin master

3. gh-pages 패키지 설치

깃허브 페이지 생성을 도와주는 패키지
배포하고 싶은 프로젝트 폴더 경로에 gh-pages를 설치

npm install gh-pages

4. package.json 수정

homepage 항목 추가
{
"homepage" : "https://(GitHub ID).github.io/(Repository name)/"
}

package.json 파일에 homepage 항목을 추가한다. 주소 형식은 위와 같이 설정해야 한다. Repository name엔 GitHub 저장소 생성 시 입력했던 이름을 그대로 입력해야 하고, 깃허브 아이디와 저장소 이름은 영문 소문자와 _, - 만 가능하다.

script 추가
"script": {
"predeploy": "npm run build",
// 배포 전에 build가 되어있지 않다면 build부터 실행
"deploy": "gh-pages -d build"
// 깃허브 페이지에 build 폴더를 업로드하겠다는 의미
}

5. 빌드 결과물 배포

npm run deploy
= npm run build -> npm run gh-pages -d build

빌드 결과물 배포

Published! 라고 출력되면 배포에 성공
코드 수정이 있어 다시 배포해야 할 때도 동일한 명령어를 입력한다.

배포가 성공적으로 완료되었다면 gh-pages라는 branch가 자동으로 생성되며, 해당 branch를 선택하면 build 파일들이 업로드 되어있는 것을 확인할 수 있다. 깃허브 페이지용 파일임.

6. GitHub Pages 세팅

Settings - Pages - Branch의 Select branch -> gh-pages로 변경

7. GitHub Pages 접속

6번 사진의 상단에 Your site is live at "" 이 호스팅 주소이다
아까 package.json 파일의 homepage에 입력한 주소와 비교한 후 잘 배포됐는지 접속해본다. 무료 호스팅이다보니 경우에 따라 업로드 결과가 자신의 사이트에 반영되기까지 몇 분 정도 걸릴 수 있다.

"https://(GitHub ID).github.io/(Repository name)/"

“https://(GitHub ID).github.io/” 주소로 바로 연결되게 하고 싶으면 깃허브 저장소 생성 시 Repository name에 “(GitHub ID).github.io”로 생성을 하면 된다.

8. 수정 후 GitHub Pages 재배포

npm run deploy
= npm run build -> npm run gh-pages -d build


호스팅을 완료하고 10분정도 기다렸다가 링크로 접속했는데 아무것도 뜨지않아요!

react 프로젝트 진행 시 react router dom을 사용하여 제작했을 경우,

<Route path="/" element={<CoinListPage />} />

위의 / 경로는 “https://(GitHub ID).github.io/” 를 의미한다.
하지만 우리는 "https://(GitHub ID).github.io/(Repository name)/" 로 접속해야 하기 때문에 아무런 화면이 뜨지 않는것

방법1.

<BrowserRouter basename={process.env.PUBLIC_URL}>

basename={process.env.PUBLIC_URL}는 package.json의 homepage URL값으로 설정

방법2.

gh-pages 에서는 BrowserRouter 대신 HashRouter 을 쓰는 것을 권장하기 때문에 BrowserRouter 대신에 HashRouter를 사용
하지만 주소에 #이 붙는다는 단점이 있음


SPA 다른 페이지로 화면 이동 후 새로고침을 하면 404에러가 떠요!

해결방법 - 404.html, index.html 참고

  1. 404.html 추가
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // MIT License
      // https://github.com/rafgraph/spa-github-pages
      // This script takes the current url and converts the path and query
      // string into just a query string, and then redirects the browser
      // to the new url with only a query string and hash fragment,
      // e.g. https://www.foo.tld/one/two?a=b&c=d#qwe, becomes
      // https://www.foo.tld/?/one/two&a=b~and~c=d#qwe
      // Note: this 404.html file must be at least 512 bytes for it to work
      // with Internet Explorer (it is currently > 512 bytes)

      // If you're creating a Project Pages site and NOT using a custom domain,
      // then set pathSegmentsToKeep to 1 (enterprise users may need to set it to > 1).
      // This way the code will only replace the route part of the path, and not
      // the real directory in which the app resides, for example:
      // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
      // https://username.github.io/repo-name/?/one/two&a=b~and~c=d#qwe
      // Otherwise, leave pathSegmentsToKeep as 0.
      var pathSegmentsToKeep = 0;

      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
        l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
        (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );

    </script>
  </head>
  <body>
  </body>
</html>
  1. index.html의 head부분 추가
    <!-- Start Single Page Apps for GitHub Pages -->
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // MIT License
      // https://github.com/rafgraph/spa-github-pages
      // This script checks to see if a redirect is present in the query string,
      // converts it back into the correct url and adds it to the
      // browser's history using window.history.replaceState(...),
      // which won't cause the browser to attempt to load the new url.
      // When the single page app is loaded further down in this file,
      // the correct url will be waiting in the browser's history for
      // the single page app to route accordingly.
      (function(l) {
        if (l.search[1] === '/' ) {
          var decoded = l.search.slice(1).split('&').map(function(s) { 
            return s.replace(/~and~/g, '&')
          }).join('?');
          window.history.replaceState(null, null,
              l.pathname.slice(0, -1) + decoded + l.hash
          );
        }
      }(window.location))
    </script>
    <!-- End Single Page Apps for GitHub Pages -->

MIT license 의 오픈 소스이기 때문에 반드시 프로젝트 포함시 라이센스를 명시!

profile
웹개발자

0개의 댓글