Vite打包后直接使用浏览器打开,显示空白问题

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

一、问题:

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

二、原因:

1、资源路径错误:

vite.config.js 配置 base: “./” (在webpack中则配置publicPath: "./"即可)

2、跨域错误

script不支持file://协议跨域, 主要是因为esModule问题。

三、解决

  1. 安装 npm install @vitejs/plugin-legacy
  2. 配置 vite.config.js
import legacy from "@vitejs/plugin-legacy"
...
export default defineConfig({
  base: './',
  plugins: [
    vue(),
    legacy({
      targets: ["ie>=11"],
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"], //解决跨域警告
    })
  ],
 build:{
    target: ['es2015', 'chrome63'], // 默认是modules,百度说是更改这个会去输出兼容浏览器
  }
...
});

3. 完成以上步骤,通过npm run build打包后的项目,可以直接访问index.html查看静态页面了,但是如果打开控制台,还是会有跨域的报错问题;

手动修改:

  • 编辑器打开打包后dist文件夹中的index.html文件
  • 删除包含type="module"的标签
  • <script>标签里面的nomodulecrossorigin 属性删掉
  • data-src换成src

自动修改

在dist并列的文件夹中创建脚本文件 (用于替换module等关键词,省的每次得手动删除)toFile.mjs
创建 toFiles.mjs (为啥格式不是js为了执行命令不报兼容的错误)

import fs from 'fs';

console.time('转换耗时');
const distPath = './dist/index.html';//打包路径的index.html
let htmlText = fs.readFileSync(distPath, 'utf8');
let resultText = '';
let htmlArr = htmlText.match(/.*\n/g) || [];
htmlArr.forEach(str => {
    str = str.replace(/\s?nomodule\s?/g,' ');
    str = str.replace(/\s?crossorigin\s?/g,' ');
    str = str.replace(/data-src/g,'src');
    if(!/type="module"/i.test(str)) resultText += str;
});
fs.writeFileSync(distPath,resultText,'utf8');
console.timeEnd('转换耗时');

package.json命令改为:"build": "vite build && node toFile.mjs",
 npm run build 之后打开index.html文件 。

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值