Deploy a Vite + React app to GitHub pages

Mohammad MaasirMohammad Maasir
2 min read

Once you are done with your react project, you would like to showcase it online, both the output as well as the source code.

Since the majority of us will be pushing our code on GitHub, why not deploy it using GitHub pages?

Here's an example: maasir554.github.io/currency-app-react

Source code: maasir554/currency-app-react

Step 1: configure for gh-pages

  1. Install the node package gh-pages as a dev-dependency.

     npm i gh-pages --save-dev
    
  2. modify package.json: add "homepage" and the following two scripts.

     {
     "homepage": "https://username.github.io/your-repository-name",
     // ...
     // ...
     "scripts": {
         "predeploy":"npm run build",
         "deploy":"gh-pages -d dist",
         // ...
         // ... 
       },
     // ...
     // ... 
     }
    

    here, username is your GitHub username and your-repo-name is the name of the repository that you will make on GitHub.

  3. modify vite.config.js: add your repo-name as "/repo-name/" in the base property

     // ...
     // ...
     export default defineConfig({
       plugins: [react()],
       base:"/your-repository-name/" //This is Important!
        // here, your-repository-name represents the GitHub repository name.  
     })
    

Step 2: push your code to GitHub

  1. First, make a new repository on GitHub. suppose the name you give is: your-repository-name

  2. in your project's root directory, initialize a git repo.

git init
git add .
git commit -m "First Commit"
git branch -M main
git add origin https://github.com/username/your-repository-name.git
git push --set-upstream origin main

here, replace the username with your GitHub username. and your-repository-name with the actual Repository name given by you.

Step 3: Deploy!

  1. navigate to github.com/username/your-repository-name/settings/pages

  2. then, select deploy from a branch option

  3. choose the branch named gh-pages for deployment instead of the main branch.

  4. Now, In the root directory of your project, you can run the following command for deploying.

npm run deploy

wait for some time, until it outputs: Published. Wait for another 30 seconds, for the server to process. Your project is now deployed.

Here we go! you can now open the link: https://username.github.io/your-repo-name/

Thanks.

Feel free to ask anything, or suggest any corrections.

1
Subscribe to my newsletter

Read articles from Mohammad Maasir directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohammad Maasir
Mohammad Maasir