Search code examples
reactjsgithub-pagesvite

Github pages react wrong routing


I have deployed a react js website to github pages here https://marknjoroge.github.io/Elizabeth-Law-Firm/. The site is just blank and the console shows the following error:

GET https://marknjoroge.github.io/assets/index-ecb5047a.js net::ERR_ABORTED 404

From the error, I can see that it is trying to get my assets from my https://marknjoroge.github.io/ instead of https://marknjoroge.github.io/Elizabeth-Law-Firm.

Here is my code

package.json

{
  "homepage": "https://marknjoroge.github.io/Elizabeth-Law-Firm",
  "name": "elizabeth-firm",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d dist"
  },

main.js

ReactDOM.createRoot(document.getElementById('root')).render(
    <React.StrictMode>
        <HashRouter basename={process.env.PUBLIC_URL}>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/contact" element={ <Contact/> } />
                <Route path="/about" element={<About />} />
                <Route path="/practices" element={<PracticeAreas />} />
            </Routes>
        </HashRouter>
    </React.StrictMode>
)

Please help.


Solution

  • found the solution on Vite's website https://vitejs.dev/guide/static-deploy.html#github-pages

    Set the correct base in vite.config.js ... If you are deploying to https://USERNAME.github.io/REPO/, then set base to '/REPO/'

    vite.config.js

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react()],
      base: '/Elizabeth-Law-Firm/',
    })