无法将Vite+React应用发布至GitHub Pages问题求助
Vite+React 部署到GitHub Pages后空白页问题
我之前成功按照文档将静态站点发布到GitHub Pages,现在尝试部署Vite+React应用,站点地址为https://mattazz.github.io/npc-gen/。构建和发布流程都能成功完成,但打开页面后显示空白,控制台出现以下错误:
GET https://mattazz.github.io/assets/index-24f5ab68.js net::ERR_ABORTED 404 GET https://mattazz.github.io/assets/index-1a0b6476.css net::ERR_ABORTED 404 mattazz.github.io/:1 Unchecked runtime.lastError: The message port closed before a response was received.
构建文件夹结构如下:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rubik+Iso" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>NPC Generator</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.jsx"></script> </body> </html>
package.json
{ "homepage": "http://mattazz.github.io/npc-gen", "name": "vite-project", "private": false, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "predeploy": "npm run build", "deploy": "gh-pages -d dist", "build": "vite build", "preview": "vite preview" }, "dependencies": { "bootstrap": "^5.2.3", "dotenv": "^16.0.3", "jspdf": "^2.5.1", "openai": "^3.2.1", "react": "^18.2.0", "react-bootstrap": "^2.7.2", "react-dom": "^18.2.0", "react-router-dom": "^6.9.0" }, "devDependencies": { "@types/react": "^18.0.27", "@types/react-dom": "^18.0.10", "@vitejs/plugin-react": "^3.1.0", "gh-pages": "^5.0.0", "vite": "^4.1.0" } }
vite.config.js
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], build: { chunkSizeWarningLimit: 1600, }, })
解决方法
问题核心是资源路径配置错误:Vite构建时未添加项目子路径/npc-gen/,导致浏览器去根域名下查找资源,返回404错误。
- 修改vite.config.js,添加
base配置指定项目基础路径:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], build: { chunkSizeWarningLimit: 1600, }, base: '/npc-gen/' // 新增该行,对应GitHub Pages的项目子路径 })
修正index.html中的资源路径,将绝对路径改为相对路径:
把<link rel="icon" type="image/svg+xml" href="/vite.svg" />修改为<link rel="icon" type="image/svg+xml" href="./vite.svg" />重新构建并部署:
npm run build npm run deploy
注:package.json中的homepage是Create React App的配置项,对Vite来说并非必需,可保留或删除,不影响构建结果。
内容的提问来源于stack exchange,提问作者Mattazz
相关产品推荐
相关产品推荐

