Vue3 Vite项目打包后,双击dist中index无法打开网页(以file协议访问)

本人需求是将vue+vite项目打包后,可以直接通过双击dist中index.html打开网页,也就是以(以file协议访问),达到类似原生html的效果。目的是为了将该网页嵌入到其他程序中,且能通过file协议访问本地路径图片。默认的打包方式不支持直接打开,需要开服务来访问。实现思路是通过plugin-legacy来实现

1、安装 plugin-legacy

npm install @vitejs/plugin-legacy

2、配置vite.config.js,添加如下内容

        

export default defineConfig({
        plugins: [
                legacy({
                        targets: ['defaults', 'not IE 11']
                }),
                vue(),
        ],
        base: './',
        build:{
                target: ['es2015', 'chrome63'],
        },

        

 其中base 配置是为了解决打包后index文件中引用的js/css路径问题

其他两项配置是为了打包后生成对应的兼容代码

   

3、在dist并列的文件夹中创建脚本文件 ,用于替换module/crossorigin 等关键词,删除含有 type="module" 的标签

在dist统计目录下创建update-Index.mjs脚本文件,写入自动处理index的脚本代码,避免每次手动修改

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('转换成功');

运行改脚本需要安装 fs

npm install fs

4、在package.json中新增打包脚本 build-localhost,脚本内容如下

"build-localhost": "vite build && node update-index.mjs"

5、运行build-localhost脚本打包

  直接运行新增打包脚本进行打包,打包后进入dist目录中,双击运行index.html就可以直接造浏览器中查看网站了。

6、如果双击运行后出现空白页面问题,需要将路由改为哈希模式 createWebHashHistory

        运行出现空白页面是因为router-view的组件没有加载上去导致的,直接将createWebHistory改为createWebHashHistory

参考文章:

Vue3 Vite项目打包静态文件之后无法以file协议访问
vite打包静态文件打开显示空白的解决

  • 26
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值