Deploying a Vite App to a GitHub Pages Subdirectory

Deploying a single-page application (SPA) like a React site built with Vite to a subdirectory of an existing GitHub Pages site...

By default, Vite assumes your application is being served from the root path (`/`). front-end routers like React Router need to be aware of the subpath, or else they will fail to map subpaths

You will need to update vite.config.ts

Vite needs to know the base public path when it builds your assets. Setting the base configuration property ensures that all generated JS and CSS file paths correctly prefix your subdirectory.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  base: '/my-cool-subdir/', 
})

After that, you will need to update your React Router Basename

If you're using React Router (react-router-dom), your BrowserRouter needs to be informed of the base path. Otherwise, navigating to /my-cool-subdir/ will throw a "No routes matched location" error.

import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter basename="/typing">
      <div className="app-container">
        <Routes>
          <Route path="/" element={<LandingPage />} />
          <Route path="/play" element={<TypingGame />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

Once your config files are updated, you can build your application:

npm run build

This generates a dist/ folder which you can simply copy to the corresponding folder on your main `github.io` repository and push the changes.

cp -r dist/ ~/path/to/my-repo.github.io/my-cool-subdir
cd ~/path/to/my-repo.github.io/my-cool-subdir
git add my-cool-subdir/
git commit -m "Deploying to subdirectory"
# yolo
git push 

And that's... it. GitHub Pages will now serve the bundled index.html from that directory