解决Vite+Vue3打包项目本地运行html白屏和报错问题
一、问题
- 通过
Vite+Vue3
创建好且未调用后端接口的项目进行打包后,想在本地直接打开打包好dist
文件夹内的index.html
文件,发现通过浏览器打开后是空白页面,且控制台报错; - 现想打包后,直接通过浏览器访问
index.html
能正常出现静态网页,且浏览器不报错。
二、解决
1.解决index.html
打开后空白的问题
- 给该项目安装
@vitejs/plugin-legacy
| npm install @vitejs/plugin-legacy --save |
复制
| import legacy from "@vitejs/plugin-legacy" |
| ... |
| export default defineConfig({ |
| plugins: [ |
| vue(), |
| legacy({ |
| targets: ["ie>=11"], |
| additionalLegacyPolyfills: ["regenerator-runtime/runtime"], |
| }) |
| ], |
| base: './', |
| ... |
| }); |
复制
- 修改路由部分,将
history
路由修改为hash
,在router
的index.js
文件中修改路由配置
| import { |
| createRouter, |
| createWebHashHistory, |
| } from 'vue-router'; |
| ... |
| const routes = [{ |
| ... |
| }]; |
| const router = createRouter({ |
| history: createWebHashHistory(), |
| routes |
| }); |
| export default router; |
复制
- 完成以上步骤,通过
npm run build
打包后的项目,可以直接访问index.html
查看静态页面了,但是如果打开控制台,还是会有跨域的报错问题;
2.解决打包后index.html
文件,控制台报错
- 编辑器打开打包后
dist
文件夹中的index.html
文件 - 删除包含
type="module"
的标签 - 把
<script>
标签里面的nomodule
,crossorigin
属性删掉 - 将
data-src
换成src