问题现象
使用 Vue3 + Vite + vue-router 的项目在本地开发正常,但打包部署到服务器后:
- 直接访问首页正常
- 通过路由跳转页面正常
- 手动刷新页面时出现白屏
- 控制台可能显示 404 错误或资源加载失败
核心原因分析
1. 路由模式与服务器配置冲突
Vue-router 使用 createWebHistory()
,实际使用的是浏览器原生 History API。
这种模式需要服务器配合处理非根路径的请求,否则刷新时服务器会尝试查找不存在的物理文件。
2. Vite 基础路径配置
javascript
// vite.config.js
export default defineConfig({
base: '/this/is/a/path/', // 该路径必须与部署目录完全一致
})
3. Vue Router 配置
javascript
const router = createRouter({
history: createWebHistory('/this/is/a/path/'), // 与 Vite base 配置一致
routes
})
解决方案
1. 验证配置一致性
配置项 | 正确示例 | 验证方法 |
---|---|---|
Vite base | /this/is/a/path/ |
检查打包后的 index.html 资源路径 |
Router history | createWebHistory('/this/is/a/path/') |
检查路由初始化代码 |
实际部署路径 | http://domain.com/this/is/a/path/ |
检查服务器部署目录 |
📌 注意:所有路径配置必须保持完全一致 ,特别注意结尾的
/
2. 服务器配置示例
Nginx 配置
nginx
location /this/is/a/path/ {
# 指向打包后的目录
alias /your/project/dist/;
try_files $uri $uri/ /this/is/a/path/index.html;
# 开启 gzip
gzip on;
gzip_types text/plain application/xml application/javascript text/css;
}
Apache 配置(.htaccess)
htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /this/is/a/path/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /this/is/a/path/index.html [L]
</IfModule>
3. 验证资源加载路径
打开浏览器开发者工具,检查以下资源是否正常加载:
- JS/CSS 文件路径
- 图标等静态资源
- 异步加载的 chunk 文件
正确路径示例:
ruby
https://your-domain.com/this/is/a/path/assets/index.123abc.js
4. 处理静态资源 404
如果出现静态资源 404,可尝试以下方案:
javascript
// vite.config.js
export default defineConfig({
build: {
assetsDir: 'static', // 将资源分类到 static 目录
rollupOptions: {
output: {
assetFileNames: 'static/[name]-[hash][extname]'
}
}
}
})
常见错误排查表
错误现象 | 可能原因 | 解决方案 |
---|---|---|
所有页面显示 404 | 服务器未指向正确目录 | 检查服务器配置的 root/alias |
仅刷新时白屏 | 缺少 try_files/rewrite 规则 | 添加 history fallback 配置 |
部分资源 404 | base 路径不一致 | 统一所有路径配置 |
控制台显示路由错误 | 路由配置路径冲突 | 检查路由的 path 定义 |
开发环境正常,生产环境异常 | 环境变量未正确处理 | 检查 .env 文件配置 |
进阶优化
动态路径配置
arduino
// vite.config.js
export default defineConfig({
base: process.env.NODE_ENV === 'production'
? '/this/is/a/path/'
: '/'
})
自定义 404 页面处理
php
// router.js
const router = createRouter({
history: createWebHistory('/this/is/a/path/'),
routes: [
// ...
{
path: '/:pathMatch(.*)*',
component: () => import('@/views/404.vue')
}
]
})
部署路径健康检查
js
// main.js
if (import.meta.env.PROD) {
const expectedBase = '/this/is/a/path/';
const currentPath = window.location.pathname;
if (!currentPath.startsWith(expectedBase)) {
window.location.replace(expectedBase);
}
}
原理图示
rust
浏览器请求 -> 服务器 -> 检查物理文件
├── 存在 -> 返回文件
└── 不存在 -> 返回 index.html (SPA 入口)