首页 前端知识 解决Vite Vue3打包项目本地运行html白屏和报错问题

解决Vite Vue3打包项目本地运行html白屏和报错问题

2024-09-08 02:09:09 前端知识 前端哥 491 188 我要收藏

解决Vite+Vue3打包项目本地运行html白屏和报错问题

一、问题

  • 通过Vite+Vue3创建好且未调用后端接口的项目进行打包后,想在本地直接打开打包好dist文件夹内的index.html文件,发现通过浏览器打开后是空白页面,且控制台报错;
  • 现想打包后,直接通过浏览器访问index.html能正常出现静态网页,且浏览器不报错。

二、解决

1.解决index.html打开后空白的问题

  • 给该项目安装@vitejs/plugin-legacy
npm install @vitejs/plugin-legacy --save
  • vite.config.js文件中加入如下配置
import legacy from "@vitejs/plugin-legacy"
...
export default defineConfig({
  plugins: [
    vue(),
    legacy({
      targets: ["ie>=11"],
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
    })
  ],
  base: './',
...
});
  • 修改路由部分,将history路由修改为hash,在routerindex.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>标签里面的nomodulecrossorigin 属性删掉
  • data-src换成src
转载请注明出处或者链接地址:https://www.qianduange.cn//article/17878.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!