DEV Community

Cover image for Deploying a Static Site (feat.Vite, gh-pages)
Nily
Nily

Posted on

1

Deploying a Static Site (feat.Vite, gh-pages)

다시 React 공부를 시작했다.

간단한 토이 프로젝트를 만들어 gh-pages로 간단히 배포하려고 했는데, 여기서 이슈가 발생했다.

배포후 확인해보니 404 not found error가 뜨는 것!

구글링 하다가 vite 관련 해결방법을 찾았는데 vite에 익숙해질겸 해서, 우선 creae-react-app으로 만들어진 프로젝트를 vite로 migration하는 것 부터 시작했다.

(요즘은 cra보다 가볍고 빠른 vite를 사용하는 추세인 것 같다. 관련 링크)

migration하는 과정은 크게 어렵지 않았다.


하지만 vite로 migration 후, 위 해결 방법을 적용해도 빈 페이지가 나오는 이슈는 여전히 있었다😅

다른 방법들을 다 적용해봐도 해결을 못하고 있던 중에, React Router path와 관련되어 있다는 것을 찾았다. (관련 링크)

vite.config.ts 파일에 basename은 /repoName/으로 설정되어있는데, router의 basename은 추가로 설정하지 않았기 때문에 /로 되어 있다는 게 원인이었다.

// vite.config.ts

export default defineConfig({
    base: '/<repoName>/',
    plugins: [react(), viteTsconfigPaths()],
    server: {    
      open: true,
      port: 3000, 
    },
})
Enter fullscreen mode Exit fullscreen mode

따라서, router의 basename을 아래와 같이 조건에 맞는 path로 변경해주면 된다.

import { createBrowserRouter, RouterProvider } from 'react-router-dom'

function App() {
 const routes = [...];

  const router = createBrowserRouter(routes, { basename: import.meta.env.DEV ? '/' : '/repoName/' })

  return <RouterProvider router={router} />
}
Enter fullscreen mode Exit fullscreen mode

import.meta.env.DEV는 Vite에 내장된 환경변수로, dev 모드일 때 값을 return 한다.


이 이슈를 해결하기 위해, 때문에 꼬박 하루를 사용했다.

초반엔 당연히 배포 설정 문제일 거라 생각하고 gh-pages 관련 이슈 위주로 찾아봤었다. router path 문제였을 줄이야...

위 블로그에도 나와있지만, 404 not found error 메시지가 화면에 뜨는데 console에선 어떤 에러도 보이지 않아서 더욱 의심하지 않았던 것 같다.

나와 같은 이슈를 겪는 사람들에게 도움이 되길 바라며..!!🤓

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay