解决Vite打包后直接使用浏览器打开,显示空白问题
Vite打包后直接使用浏览器打开,显示空白
1.需求
安卓webview等浏览器直接打开文件显示
2.原因
(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({
....
plugins: [legacy({
targets: ['defaults', 'not IE 11']
}),vue()],
build:{
target: ['es2015', 'chrome63'], // 默认是modules,百度说是更改这个会去输出兼容浏览器,尝试没啥作用,先配置吧
}
....
})
3.在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('转换耗时');
4.package.json命令改为:
"build": "vite build && node toFile.mjs",
npm run build 之后打开index.html文件:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue2移动端使用vue-qrcode-reader实现扫一扫功能的步骤
最近在使用vue开发的h5移动端想要实现一个调用摄像头扫描二维码的功能,所以下面这篇文章主要给大家介绍了关于vue2移动端使用vue-qrcode-reader实现扫一扫功能的相关资料,需要的朋友可以参考下2023-06-06
vue3 + async-validator实现表单验证的示例代码
表单验证可以有效的过滤不合格的数据,减少服务器的开销,并提升用户的使用体验,今天我们使用 vue3 来做一个表单验证的例子,需要的朋友跟随小编一起学习下吧2022-06-06


最新评论