DEV Community

Cover image for How to deploy ReactJS Apps (built using Vite) on GitHub Pages?
Shrinivas Vishnupurikar
Shrinivas Vishnupurikar

Posted on

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

[ Technology ]: ReactJS – Article #2


Differences in build tools lead to hurdles, especially in deployment. Today we'll spotlight one such and solve it for you.

You gather requirements, you design, you develop and you test. Great! Now you'll barely move to deployment.

Just kidding. I know, deploying dynamic, feature rich, robust ( and 50 other adjectives ) apps that use backend and databases is quite tricky. Hence, as a starter we're going to learn how to deploy a simple ( too simple ) ReactJS App.

Where are we deploying it? GitHub Pages! Yes, GitHub is not only scoped to hosting the project's source code or GitHub Pages to host static websites that are purely HTML5 + CSS3 + JS.

Where else could you deploy your front-end apps in general?
The list of platforms is as follows:


Creating a ReactJS App! The Confusion Spiral.

If you're living in 2024, I hope you don't use npx create-react-app <app-name> to create ReactJS App.

If you look at the ReactJS's official docs, you'll see that there's no option to create a pure ReactJS App, but they'll insist you to create project using Next.js, Remix, Gatsby and more.

Why the sudden shift away from npx create-react-app?
Although, it was a fantastic starting point for many React developers, the landscape of frontend development has evolved significantly due it's limitations with respect to the following:

  • Opinionated Structure
  • Difficulty in Customization
  • Performance Overhead

Thus developers resorted to other and better alternatives which were as follows:

  • Vite: This build tool has gained immense popularity due to its lightning-fast development server, efficient bundling, and flexibility.

  • Next.js: While primarily a React framework, it offers a robust set of features for building web applications, including server-side rendering, static site generation, and routing.

  • Gatsby: Another popular static site generator built on React, offering performance and SEO benefits.

I now get it that NextJS Apps are in the end ReactJS Apps, because, NextJS is a framework built on-top-of ReactJS library.

But either way, if you didn't want to create a framework app (NextJS App) but a library app (ReactJS App), ( which is something I did ), you could using Vite build tool to do so.

Creating a ReactJS App using Vite
You can use the following command in the terminal to create a React App that uses JavaScript ( by default ) in one-go.

If you didn't know, React officially supports TypeScript.

npm create vite@latest deploy-reactjs-app-with-vite -- --template react
Enter fullscreen mode Exit fullscreen mode

Or you could use the following command to create a ReactJS Apps by step-by-step process:

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

Setting the GitHub Up!

Let's create a Remote GitHub Repository. Got to your GitHub Profile and create a remote GitHub Repository and you should be able to see the following interface for an empty repo:

Initial Git Repo's Impression

If you go to the Settings => Pages tab of your GitHub repo, you'll see the following interface:

Viewing Branches for our Repo

It shows either main branch or None. Right now, you don't have to be concerned about it, but be aware that we're going to revisit this page again.

Once you work on the project, I want you to execute the following commands (sequentially, of course) in your working directory:

  1. Initialize an empty git repo on your local system.
git init
Enter fullscreen mode Exit fullscreen mode
  1. Track All file by staging them.
git add .
Enter fullscreen mode Exit fullscreen mode
  1. Create a Checkpoint that takes a snapshot of current progress of the stages file(s) in above:
 git commit -m "Added Project Files"
Enter fullscreen mode Exit fullscreen mode
  1. Connect local repo (on our system) with the remote repo (the one created on GitHub).
 git remote add origin url_of_the_remote_git_repo_ending_with_.git
Enter fullscreen mode Exit fullscreen mode
  1. Upload the progress made till our checkpoint from local repo to the remote repo.
 git push -u origin main

Enter fullscreen mode Exit fullscreen mode

Once you successfully push the changes to the remote repository, you'll the following output in your terminal:

Successful Acknowledgement for Pushing Changes

Now, if you refresh the GitHub Repository the interface would look something as follows:

Upload Files visible on GitHub


Installing Dependencies and Crying over Errors:

Step 1: Installing gh-pages package

Right now we have just made 1 checkpoint and pushed it to our remote repo. We have NOT started to work on the deployment! YET!

Head to your working directory in your integrated terminal and fire up the following command:

npm install gh-pages --save-dev
Enter fullscreen mode Exit fullscreen mode

This command will install and save gh-pages (github-pages) as a dev dependency or our project.

Dependencies are packages required for the application to run in production. Dev dependencies are packages needed only for development and testing.

Once completed, the terminal will look as follows (provides some positive acknowledgement):

Successful Installation of gh-pages dependency

Step 2: Update package.json

You have to add the following code to your package.json file.

{
    "homepage": "https://<username>.github.io/<repository>",
    "scripts": {
        "predeploy": "npm run build",
        "deploy": "gh-pages -d build",
        // ... other scripts
    }
    // other scripts
}
Enter fullscreen mode Exit fullscreen mode

The above scripts are not specified during the project installation via Vite as they are gh-pages specific scripts.

The explanation for each is as follows:

  • homepage: The "homepage" field in the package.json file of a React project specifies the URL at which your app will be hosted. This field is particularly important when deploying a React application to GitHub Pages or any other static site hosting service that serves the site from a subdirectory.

Do update the values of <username> and <repository> of the homepage property. In my case the values are ShrinivasV73 and Deploy-ReactJS-App-With-Vite respectively.

It is good to consider that the value are case-sensitive and should be placed accordingly.

  • "scripts" field in package.json allows you to define custom scripts that can be run using npm run .

    • "predeploy": "npm run build": This script runs automatically before the deploy script and it triggers the build process of your project.
    • "deploy": "gh-pages -d build": This script is used to deploy your built application to GitHub Pages. It uses the gh-pages package to publish the contents of the specified directory (build in this case) to the gh-pages branch of your GitHub repository.

Step 3: Deploy The App

Now that we've updated scripts as well, it is time to deploy the project. Head to the terminal and fire-up the following command to process:

npm run deploy
Enter fullscreen mode Exit fullscreen mode

Encountering Error During Deployment

And boom 💥, WE GET AN ERROR!

Error: ENOENT: no such file or directory, stat '<working-drectory>/build'
Enter fullscreen mode Exit fullscreen mode

npm (node package manager) is trying to access the folder named build via the command npm run deploy which is actually npm run gh-pages -d build executed behind the scenes.

But it can't find any.

Bug Fix: #1 Updating the package.json file

Remember we didn't create a build directory by ourselves throughout this journey.

Vite outputs the build files to a dist directory by default and not the built directory, whereas tools like CRA (create-react-apps) use a build directory.

( This is exactly where the underlying functions and processes of different build tools manifests. )

We simply have to replace the build with dist in the deploy script inside the package.json file.

{ 
    "homepage": "https://<username>.github.io/<repository>", 
    "scripts": { 
        "predeploy": "npm run build", 
        "deploy": "gh-pages -d dist", 
        // ... other scripts } 
    // other scripts 
}
Enter fullscreen mode Exit fullscreen mode

Bug Fix #2: Updating the vite.config.js

By default your vite.config.js file looks as follows:

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

export default defineConfig({
    plugins: [react()],
});
Enter fullscreen mode Exit fullscreen mode

To make our app functions as expected without any bugs after successful deployment, we need to add base: '/Deploy-ReactJS-App-With-Vite/' to the object, which is passed to the defineConfig() method.

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

export default defineConfig({
    plugins: [react()],
    base: '/Deploy-ReactJS-App-With-Vite/',
});
Enter fullscreen mode Exit fullscreen mode

Setting the base property in vite.config.js is crucial for deploying a Vite-built app to a subdirectory, such as on GitHub Pages. It ensures that all asset paths are correctly prefixed with the subdirectory path, preventing broken links and missing resources.

Example:

  • Our repository is named Deploy-ReactJS-App-With-Vite and you are deploying it to GitHub Pages. The URL for your site will be https://username.github.io/Deploy-ReactJS-App-With-Vite/

  • If you don’t set the base property, the browser will try to load assets from https://username.github.io/ instead of https://username.github.io/Deploy-ReactJS-App-With-Vite/, resulting in missing resources.


Retry Deploying The App

Once you make the necessary changes to package.json file and vite.config.js file it's time to git add, commit, push. AGAIN!

Head to the working directory in the terminal and try deploying the app again:

npm run deploy
Enter fullscreen mode Exit fullscreen mode

And this time when the app actually gets deployed to the Github pages, you'll see again, the positive acknowledgment to the terminal itself as follows:

Positive Acknowledgement of Successful Deployment

If you refresh your GitHub repo go to the Settings => Pages tab of it, you'll see a new gh-pages branch added to the branches.

Changes Reflected about Branches on GitHub Repo

How do you access the app on web? Remember the value of homepage property in the package.json file? Yup! That's it.

In our case, it is https://ShrinivasV73.github.io/Deploy-ReactJS-App-With-Vite/


Conclusions

Congratulations! You've successfully learned how to deploy ReactJS App with Vite on GitHub Pages.

My recommendation for you folks would be to experiment as follows in different ways:

  • Create different font-end / full-stack apps like Angular or Vue.js and see how the configurations needs to be updated according to them.

  • Create different React Apps like Next.js or Remix or Gatsby

  • Use different platforms to deploy your front-end applications like vercel or netlify to see which option suits best for which use case.

In a nutshell, I started with experimentation and summarised my learning in this article. May be its your time to do so. Cheers!

If you think that my content is valuable or have any feedback,
do let me by reaching out to my following social media handles that you'll discover in my profile and the follows:

LinkedIn: https://www.linkedin.com/in/shrinivasv73/

Twitter (X): https://twitter.com/shrinivasv73

Instagram: https://www.instagram.com/shrinivasv73/

Email: shrinivasv73@gmail.com


Top comments (0)