리액트 - json-server - Github Pages에 React 호스팅하기

반응형

하고자 하는 것

협업하는 기획자나 디자이너 등 다른 직군이 개발중인 페이지에 접근하며 진행도 파악을 할 수 있게 하고 싶다.

해결방법으로는 최근 스토리북 등 다양한 방법이 있겠지만 나는 Github Pages를 통해 React 페이지를 띄워보려고 한다.

Storybook: UI component explorer for frontend developers
Storybook is an open source tool for developing UI components in isolation for React, Vue, Angular, and more. It makes building stunning UIs organized and efficient. "Storybook is a powerful frontend workshop environment tool that allows teams to design, build, and organize UI components (and even full screens!)
https://storybook.js.org/

💡
Github Pages란? GitHub Pages는 GitHub 저장소(repository)를 이용해 웹 사이트를 무료로 호스팅해주는 서비스로서 GitHub에서 제공하고 있다. 사용자가 GitHub 저장소에 자신의 웹 프로젝트 빌드 결과물을 업로드하면 GitHub가 그 결과물을 호스팅하는 원리이다. 웹 호스팅이 무료라곤 하지만 일반 사용자는 public 저장소에 대해서만 무료로 호스팅할 수 있고, private 저장소를 호스팅하고 싶으면 GitHub Pro 이상의 계정을 구매해야 한다. 참고 : https://stackoverflow.com/questions/28744980/github-pages-for-private-repository 출처: https://velog.io/@gwak2837/GitHub-Pages-gh-pages%EB%A1%9C-%EB%AC%B4%EB%A3%8C-%EC%9B%B9-%ED%98%B8%EC%8A%A4%ED%8C%85%ED%95%98%EA%B8%B0

진행 방법

가정 - 자신이 생성한 react app이 있고 해당 앱이 특정 레포지토리에 '공개(public)'로 올려져 있다고 가정한다.

  1. 자신의 해당 react app이 있는 깃허브 레포로 들어가서 Settings로 들어간다.

2. 아래로 드래그해서 내려가다 보면 Github Pages 란이 보이고 아무것도 설정 안해줬으니 Source가 None으로 되어 있는 것을 확인 가능하다.


3. master나 main의 브랜치를 선택해서 Save를 누른다.

💡
(내 생각인데 이전에 아예 Github Pages 부분 설정할 만한 Github Pages용 브랜치를 생성해준 상태에서 진행해도 될 것 같다. 실제 package.json, index.js, app.js 의 파일이 수정될 여지가 있어서 아예 투 트랙으로 가도 될 것 같다.)
💡
(하지만 그만큼 실제 본 개발이 진행될때마다 주기적으로 Github Pages용 브랜치에 적용 및 수동 수정해주고 하는 번거루음이 있을 것 같다.)

4. https:// 로 시작하는 내 레포의 호스팅 주소가 생겨난 것을 알 수 있다.

우리는 이 주소를 기반으로 react app 빌드파일을 엮어주면 된다.


5. package.json에 homepage를 추가해 준다.

"devDependencies": {
        "eslint": "^7.2.0",
        "eslint-config-airbnb": "18.2.1",
        "eslint-config-prettier": "^8.0.0",
        "eslint-plugin-import": "^2.22.1",
        "eslint-plugin-jsx-a11y": "^6.4.1",
        "eslint-plugin-prettier": "^3.3.1",
        "eslint-plugin-react": "^7.21.5",
        "eslint-plugin-react-hooks": "^1.7.0",
        "prettier": "2.2.1"
    },
    "homepage": "https://seungwookhan.github.io/react-basic/" # 이런 형식

6. package.json의 scripts에 아래 2개를 추가해준다

"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject",
        "predeploy": "react-scripts build", # 추가
        "deploy": "gh-pages -d build" # 추가
    },

실제 우리는 해당 빌드 파일을 gh-pages라는 브랜치로 deploy를 할 것이다(없다면 생성됨)

7. yarn deploy를 진행한다.

yarn deploy

아마 이 글대로 따라왔다면 main이나 master 브랜치일 것이다.

확실한 건 모르지만 위의 과정을 진행했다면 당연히 package.json 파일에 변화가 생겼을 것인데,

이때 commit 및 push까지 해주고 진행하라는 얘기가 많다.

yarn deploy 이전에 commit 및 push 를 진행한다.

문제

이와 같이 빈 화면으로 렌더링되는 경우가 생겼다...

어떻게 해결할 수 있을까?

해결

루트 url 문제였다.

github에서 생성된 주소는 https://...github.io/레포 이름/ 이런식으로 구성이 되는데

실제 라우터의 '/' 는 https://...github.io/ 자리로 라우팅하게 되는 것이다.

시도 1.

Gh-pages deployment problems with react-router · Issue #1765 · facebook/create-react-app
This was referenced Jun 5, 2018 You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or window. Reload to refresh your session. Reload to refresh your session.
https://github.com/facebook/create-react-app/issues/1765#issuecomment-285114194

위 글을 참고하여 아래의 index.js 파일을 수정해줬다.

ReactDOM.render(
    <Provider store={store}>
        <Router history={history}> ### 기존 부분
        <Router basename={process.env.PUBLIC_URL} history={history}> # 수정
            <App />
        </Router>
    </Provider>,

수정 후 commit 후 push 후 yarn deploy 를 진행해줬는데 적용이 안되었다.

시도 2.

역시 위 글을 참고하여 아래의 App.js 파일을 수정해줬다.

return (
        <div>
            <Switch>
                <Route exact path="/" component={RoomsPage} /> ### 기존 부분
                <Route exact path="/room/:roomId" component={RoomPage} /> ### 기존 부분
                <Route exact path="/edit/:roomId" component={RoomPage} /> ### 기존 부분
                <Route exact path={process.env.PUBLIC_URL + '/'} component={RoomsPage} /> # 수정
                <Route exact path={process.env.PUBLIC_URL + '/room/:roomId'} component={RoomPage} /> # 수정
                <Route exact path={process.env.PUBLIC_URL + '/edit/:roomId'} component={RoomPage} /> # 수정
            </Switch>
        </div>

역시 동일하게 수정 후 commit 후 push 후 yarn deploy 를 진행해줬는데 적용이 되었다!!!

만약 yarn deploy에서 prefer-template 에러가 난다면 eslint.json에

"prefer-template": "off"

를 추가해준다.

다른 방법

  1. index.js 에서 BrowserRouter나 Router로 감싸져 있는 부분을 HashRouter로 바꿔준다.

반응형