Vue3+Router项目build后dist的index.html空白问题求助
Vue3+Vite项目build后本地打开index.html空白的原因及Netlify部署解决方案
问题现象
使用Vue3+Router+Vite开发,执行npm run dev时站点正常运行,但执行npm run build生成dist文件夹后,直接双击打开其中的index.html页面显示空白,控制台出现以下错误:
Access to script at 'file:///Z:/assets/index-64361c69.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted. Failed to load resource: net::ERR_FAILED Failed to load resource: net::ERR_FILE_NOT_FOUND
原因分析
绝对路径导致资源找不到
查看dist目录下的index.html,资源引用都是以/开头的绝对路径:<script type="module" crossorigin src="/assets/index-64361c69.js"></script> <link rel="stylesheet" href="/assets/index-9b74bc40.css">当用
file://协议直接打开文件时,浏览器会把/解析为本地磁盘的根目录(比如你的Z盘根目录),但实际assets文件夹是在dist目录下,所以浏览器找不到这些资源,导致页面空白。file://协议的CORS限制
浏览器的安全策略禁止file://协议加载跨源资源,即使资源在本地磁盘,也会触发CORS报错,因为file://不在允许的协议列表(http/https等)里。
本地测试临时解决方法
如果想在本地预览build后的效果,不要直接双击index.html,推荐两种方式:
- 用Vite自带的预览命令:在项目根目录执行
npm run preview,它会启动一个本地http服务器加载dist文件夹,资源路径和跨域问题都会自动解决。 - 修改Vite配置为相对路径:在
vite.config.ts中添加base: './',重新执行npm run build,此时dist里的资源路径会变成./assets/...,直接打开index.html也能加载资源(注意:如果用了Vue Router的history模式,本地打开还是会有路由跳转问题,建议优先用npm run preview)。
修改后的vite.config.ts示例:
import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, base: './' // 添加相对路径配置 })
Netlify部署解决方案
部署到Netlify时,只需在项目根目录创建netlify.toml文件,内容如下:
[build] command = "npm run build" publish = "dist"
这个配置告诉Netlify:执行npm run build构建项目,然后把dist文件夹作为部署的静态资源目录。Netlify会自动处理静态资源的路径问题,确保部署后的站点正常运行。
内容的提问来源于stack exchange,提问作者C.NCB
相关产品推荐
相关产品推荐

