DEV Community

Usool
Usool

Posted on

Deploying a Vite/React Application with Images: A Complete Guide

Deploying a Vite/React application on GitHub Pages is an exciting milestone, but the process can sometimes come with unexpected challenges, especially when dealing with images and assets. This blog post will walk you through the entire process, from the initial deployment to troubleshooting common problems and arriving at effective solutions.

Whether you're a beginner or someone with experience, this guide will help you avoid common pitfalls and successfully deploy your Vite/React app with all assets properly rendered.


Prerequisites

Before we dive in, make sure you have the following:

  • A Vite/React project: This guide assumes you've set up your project using Vite as the build tool and React as your framework.
  • GitHub Repository: You should have an existing GitHub repository where you'll push your application for deployment.
  • GitHub Pages Enabled: Ensure that GitHub Pages is enabled in the settings of your repository for deployment.

Step 1: Initialize the Project and GitHub Pages Deployment

First, ensure that your Vite/React application is properly initialized and works on localhost. You can create a basic Vite project as follows:

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

Install dependencies:

npm install
Enter fullscreen mode Exit fullscreen mode

Run the project locally to confirm everything works:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Once your project is ready, push it to your GitHub repository.

Create a vite.config.js for GitHub Pages

GitHub Pages expects the application to be served from a specific base URL, which is typically your repository name. Update the vite.config.js file to reflect this:

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

export default defineConfig({
  base: process.env.NODE_ENV === 'production' ? '/your-repo-name/' : '/',
  plugins: [react()],
})
Enter fullscreen mode Exit fullscreen mode

The base option ensures that the application uses the correct base path when deployed.


Step 2: Build and Deploy the Project

You’ll need to install the gh-pages package to handle the deployment.

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

In your package.json, add the following scripts to automate the deployment process:

"scripts": {
  "predeploy": "npm run build",
  "deploy": "gh-pages -d dist"
}
Enter fullscreen mode Exit fullscreen mode

Run the deployment:

npm run deploy
Enter fullscreen mode Exit fullscreen mode

At this point, your project should be live at https://<your-username>.github.io/<your-repo-name>/, but if you’re like me, you might run into some issues with the app not rendering properly, or images not showing up.


Step 3: Common Problems and Solutions

Problem 1: Blank Page After Deployment

After deploying, you might notice that the app loads a blank page. This is often caused by routing issues. By default, BrowserRouter from react-router-dom is used, which relies on server-side routing, but GitHub Pages serves static files and doesn't handle client-side routes.

Solution: Use HashRouter

To solve this, switch from BrowserRouter to HashRouter in your index.js or main.jsx file.

Note: It is not necessary you have the it is just a convenient UI library that I use very often in my projects.

import { HashRouter } from 'react-router-dom';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <ChakraProvider>
      <HashRouter>
        <App />
      </HashRouter>
    </ChakraProvider>
  </StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

HashRouter uses a hash symbol (#) in the URL to keep track of the navigation state, allowing GitHub Pages to properly serve different routes without returning a 404.


Problem 2: 404 Error on Refresh or Other Routes

After fixing the blank page issue, another problem you may face is the app working on the homepage but showing a 404 error when navigating to other routes, especially if you directly access a route like /blogs or /projects.

This happens because GitHub Pages only knows how to serve the index.html file and doesn't recognize routes managed by React Router.

Solution: Handle 404 Errors in GitHub Pages Settings

To fix this, you need to create a 404.html file in your public/ folder. This file will ensure that GitHub Pages serves your index.html file for any routes it doesn’t recognize, allowing React Router to handle routing:

  1. Copy your index.html to a new file named 404.html.
  2. Place this file in your public/ folder.
  3. Rebuild and redeploy the project.

Problem 3: Images Not Loading in Production

One of the most common deployment issues is images not loading correctly. While they work fine on localhost, you might notice broken image links after deploying to GitHub Pages.

For example, you might reference an image like this in your components:

<Image
  objectFit='cover'
  src="/Images/myImage.png"
  alt="thumbnail"
/>
Enter fullscreen mode Exit fullscreen mode

Issue: Incorrect Image Paths

The problem here is that absolute paths (starting with /) don’t work well when the app is deployed in a subdirectory (e.g., /your-repo-name/). GitHub Pages tries to find the image at https://<username>.github.io/Images/myImage.png instead of https://<username>.github.io/your-repo-name/Images/myImage.png, resulting in a 404 error.

Solution: Use BASE_URL

To fix this, move all you images into Public/Images, while that is optional, I would highly recommend you do so. The you will dynamically prepend the BASE_URL to the image paths based on the environment:

  1. Define a BASE_URL constant that depends on the environment:
   const BASE_URL = import.meta.env.BASE_URL;
Enter fullscreen mode Exit fullscreen mode
  1. Use this BASE_URL when referencing images:
   <Image
     objectFit='cover'
     src={BASE_URL + "Images/myImage.png"}
     alt="thumbnail"
   />
Enter fullscreen mode Exit fullscreen mode

NOTE: Dont forget to remove the / in front of Images, otherwise you will have it doubled, one from the BASE_URL and another from the /Images that you forgot to remove.

This ensures that the correct path is used both in development (localhost) and in production (GitHub Pages).


Step 4: Final Deployment

After implementing the fixes for routing and image paths, rebuild and redeploy your application:

npm run build
npm run deploy
Enter fullscreen mode Exit fullscreen mode

Your Vite/React application should now be fully deployed with all images correctly rendered and all routes properly handled.

In summary:

  1. Routing Issues: Use HashRouter for proper routing in static deployments like GitHub Pages.
  2. 404 Errors on Routes: Create a 404.html file to ensure GitHub Pages serves your app correctly.
  3. Images Not Loading: Move all images to Public/Images and dynamically append BASE_URL to your asset paths to handle both development and production environments.

With these steps, your Vite/React app should be live and functioning smoothly on GitHub Pages. Happy coding and deploying!

Top comments (0)