本文详解 Vite 项目使用 gh-pages 部署时因构建目录不匹配导致的 gh-pages -d build 失败问题,指出根本原因是 build 输出目录与实际生成路径不一致,并提供正确配置方案。
本文详解 vite 项目使用 gh-pages 部署时因构建目录不匹配导致的 `gh-pages -d build` 失败问题,指出根本原因是 `build` 输出目录与实际生成路径不一致,并提供正确配置方案。
在使用 gh-pages 将 Vite 项目部署到 GitHub Pages 时,常见错误如 Error: Cannot find module 'build' 或 ENOENT: no such file or directory, stat 'build',其根源往往并非权限或网络问题,而是 构建输出目录与 gh-pages 指令中指定的目录不一致。
Vite 默认的构建输出目录是 dist(而非 build),这一点可通过 vite.config.js 中的 build.outDir 字段确认(默认值即 'dist')。而你在 package.json 中配置了 "deploy": "gh-pages -d build",但执行 npm run build 后实际生成的是 dist/ 文件夹——因此 gh-pages 在 build/ 下找不到 index.html 等资源,导致部署失败。
✅ 正确做法是:确保 gh-pages -d
{
"scripts": {
"build": "vite build",
"predeploy": "npm run build",
"deploy": "gh-pages -d dist"
}
}
⚠️ 注意事项:
- 不要手动修改 build 命令为 npm run dist(dist 并非有效脚本)——原答案中 "predeploy": "npm run dist" 是错误示范,应保留 "npm run build";
- 若你已自定义 vite.config.js 将输出目录改为 build(例如 build: { outDir: 'build' }),则才需同步更新 gh-pages -d build;否则务必使用 dist;
- 首次部署前建议先运行 npm run build,检查 dist/ 目录是否存在且包含 index.html 和静态资源;
- 确保 homepage 字段(如 "https://username.github.io/repo-name")与 GitHub Pages 设置的源分支(通常是 gh-pages)和子路径匹配,否则资源可能 404。
部署验证命令:
npm run deploy
成功后,访问 https://
总结:Vite + gh-pages 的核心一致性原则是「构建输出目录 = gh-pages 指定目录」。坚持使用默认 dist 目录,配以正确的 predeploy 和 deploy 脚本,即可稳定、高效完成自动化部署。











