How to Deploy a React Project to GitHub Pages.
1. Set Up Your React Project:
- Ensure your React project is ready and working locally.
2. Install GitHub Pages Package:
Run the following command to install gh-pages
:
npm install --save-dev gh-pages
3. Configure vite.config.js
:
Update your Vite configuration to set the base
option. This ensures the app is served correctly from GitHub Pages.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
base: '/your-gh-repository-name/',
build: {
outDir: 'dist',
},
});
4. Update package.json
Scripts:
Add deployment scripts to your package.json
:
"scripts": {
"dev": "vite",
"build": "vite build",
"predeploy": "npm run build",
"deploy": "gh-pages -d dist",
"lint": "eslint .",
"preview": "vite preview"
},
5. Build and Deploy:
Run the following commands to build your project and deploy it to GitHub Pages:
npm run predeploy
npm run deploy
Configure GitHub Pages:
Go to your GitHub repository settings.
Navigate to the "Pages" section.
Set the source branch to
gh-pages
and save the settings.
Verify Deployment:
Check your GitHub Pages URL to see if your React project is live.
Ensure that all routes and assets are correctly configured to work with the base URL.
Check the console for any errors if the deployment doesn't work as expected.
Subscribe to my newsletter
Read articles from HARSHAD DONGARDIVE directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by