4. Deployment Strategies (Static Hosting)
Vite React applications generate pure static files (HTML, CSS, JS) during the build, making them easy to deploy to various static hosting services like GitHub Pages, Netlify, and Vercel.
4.1. Deploying to GitHub Pages
To deploy your Vite app to GitHub Pages, you need to add a base option to your vite.config.js. If your project name is my-react-app, use /my-react-app/.
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
base: '/my-react-app/', // Set GitHub Pages subpath
});
Deployment Steps:
- Run
npm run build. - Install and use the
gh-pagespackage.
npm install gh-pages --save-dev
// Add to package.json scripts
// "deploy": "gh-pages -d dist"
// "predeploy": "npm run build"
- Execute
npm run deployto push thedistdirectory to thegh-pagesbranch. - In your GitHub repository settings, set the GitHub Pages source to the
gh-pagesbranch.
4.2. Deploying to Netlify or Vercel
Netlify and Vercel offer automatic build and deployment features integrated with Git repositories, making the process much simpler.
- 1. Connect Repository: From your Netlify/Vercel dashboard, connect your GitHub/GitLab/Bitbucket repository.
- 2. Configure Build Settings:
- Build Command:
npm run build - Publish Directory:
dist
- Build Command:
- 3. Automatic Deployment: The service will automatically build and deploy your app every time you push code.