部署Vite构建的React项目到GitHub Pages出现空白页求助
解决Vite React项目部署GitHub Pages空白页及MIME类型错误问题
问题根源
控制台的MIME类型错误是因为GitHub Pages默认将.jsx后缀的文件识别为text/jsx类型,但浏览器期望模块脚本是application/javascript类型;同时你的base路径配置错误,导致资源加载路径异常,双重问题引发空白页。
具体解决步骤
修正Vite的base路径与构建输出配置
在vite.config.ts或vite.config.js中调整配置:import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], // 用户主页仓库(username.github.io)的base必须设为根路径"/" base: "/", build: { rollupOptions: { output: { // 强制构建输出的JS文件使用.js后缀,避免出现.jsx后缀 entryFileNames: `assets/[name].js`, chunkFileNames: `assets/[name].js`, assetFileNames: `assets/[name].[ext]` } } } });说明:你的仓库是用户主页仓库(
soheum.github.io),这类仓库的GitHub Pages会直接部署到根域名下,因此base必须设为"/",之前配置的"soheum.github.io"会导致资源路径错误。移除package.json中的homepage字段
Vite项目不需要homepage配置(该字段属于Create React App的配置项),直接删除package.json里的:"homepage": "https://soheum.github.io/soheum.github.io"重新构建并部署
- 执行构建命令:
npm run build - 检查
dist目录,确认所有JS文件均为.js后缀,无.jsx文件 - 将
dist目录下的所有内容提交并推送到GitHub仓库(或通过GitHub Actions自动构建部署)
- 执行构建命令:
可选:GitHub Actions自动部署配置
如果使用GitHub Actions自动化部署,可在仓库根目录创建.github/workflows/deploy.yml,内容如下:
name: Deploy to GitHub Pages on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: 'npm' - name: Install dependencies run: npm ci - name: Build project run: npm run build - name: Deploy to GitHub Pages uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./dist
内容的提问来源于stack exchange,提问作者So Heum Hwang
相关产品推荐
相关产品推荐

