vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3刷新白屏问题解决

Vue3+Vite项目部署后刷新白屏问题的解决方法

作者:从文处安

Vue3 + Vite 项目部署后出现了手动刷新页面时出现白屏的问题,下面小编就来和大家探讨一下白屏出现的原因以及具体的解决方法,需要的可以参考下

问题现象

使用 Vue3 + Vite + vue-router 的项目在本地开发正常,但打包部署到服务器后:

核心原因分析

1. 路由模式与服务器配置冲突

Vue-router 使用 createWebHistory(),实际使用的是浏览器原生 History API。

这种模式需要服务器配合处理非根路径的请求,否则刷新时服务器会尝试查找不存在的物理文件。

2. Vite 基础路径配置

// vite.config.js
export default defineConfig({
  base: '/this/is/a/path/', // 该路径必须与部署目录完全一致
})

3. Vue Router 配置

const router = createRouter({
  history: createWebHistory('/this/is/a/path/'), // 与 Vite base 配置一致
  routes
})

解决方案

1. 验证配置一致性

配置项正确示例验证方法
Vite base/this/is/a/path/检查打包后的 index.html 资源路径
Router historycreateWebHistory('/this/is/a/path/')检查路由初始化代码
实际部署路径http://domain.com/this/is/a/path/检查服务器部署目录

注意:所有路径配置必须保持完全一致,特别注意结尾的 /

2. 服务器配置示例

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)

<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. 验证资源加载路径

打开浏览器开发者工具,检查以下资源是否正常加载:

正确路径示例:

https://your-domain.com/this/is/a/path/assets/index.123abc.js

4. 处理静态资源 404

如果出现静态资源 404,可尝试以下方案:

// 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 配置
部分资源 404base 路径不一致统一所有路径配置
控制台显示路由错误路由配置路径冲突检查路由的 path 定义
开发环境正常,生产环境异常环境变量未正确处理检查 .env 文件配置

进阶优化

动态路径配置

// vite.config.js
export default defineConfig({
  base: process.env.NODE_ENV === 'production' 
    ? '/this/is/a/path/' 
    : '/'
})

自定义 404 页面处理

// router.js
const router = createRouter({
  history: createWebHistory('/this/is/a/path/'),
  routes: [
    // ...
    { 
      path: '/:pathMatch(.*)*', 
      component: () => import('@/views/404.vue')
    }
  ]
})

部署路径健康检查

// 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);
  }
}

原理图示

浏览器请求 -> 服务器 -> 检查物理文件
                ├── 存在 -> 返回文件
                └── 不存在 -> 返回 index.html (SPA 入口)

到此这篇关于Vue3+Vite项目部署后刷新白屏问题的解决方法的文章就介绍到这了,更多相关Vue3刷新白屏问题解决内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文