How to Deploy Vite + React to Github Pages?

A few days ago while porting some captcha library from vanillajs to react for work, I needed to share it with my colleague. The project itself was created using react and vite. Usually I use Vercel to share demo apps, but this time I was too lazy to open the Vercel dashboard and deploy there. Instead, I did a little research and found the easiest way to share the demo was using GitHub Pages.

Install gh-pages cli

Luckily there are npm packages to help us deploy our vite project to github pages. We only need to provide a prebuild script and gh-pages will do the rest, pushing our build to github pages.

Install gh-pages package

npm i gh-pages

Create prebuild script

In your package.json add this script.

    "scripts": {
      "dev": "vite",
      "build": "vite build",
+     "predeploy" : "npm run build",
+     "deploy" : "gh-pages -d dist",
    }

Register the homepage url

Next add homepage url, the format is {username}.github.com/{repo_name}:

{
+   "homepage": "https://ahmadrosid.github.io/react-slider-captcha/",
    "scripts": {
        ...
    }
}

Update vite base url

In order to make the build get correct assets path we need to setup the vite base url path. In your vite.config.js add this config.

export default defineConfig({
+  base: "https://ahmadrosid.github.io/react-slider-captcha/",
}

Run Deploy Command

Now that everything configured let's run the deployment. Type this command to execute the deployment.

npm run deploy

gh-pages cli will automatically call the prebuild command in paackage scripts and it will run the build and push the build to github pages.

And that's all very easy. You can see example project of this tutorial in : https://github.com/ahmadrosid/react-slider-captcha