本人需求是将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
参考文章: