解決Vite打包后直接使用瀏覽器打開,顯示空白問題
Vite打包后直接使用瀏覽器打開,顯示空白
1.需求
安卓webview等瀏覽器直接打開文件顯示
2.原因
(1)資源路徑錯誤
vite.config.js 配置 base: “./” (在webpack中則配置publicPath: "./"即可)
(2)跨域錯誤
script不支持file://協(xié)議跨域, 主要是因為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并列的文件夾中創(chuàng)建腳本文件 (用于替換module等關(guān)鍵詞,省的每次得手動刪除)toFile.mjs
創(chuàng)建 toFiles.mjs (為啥格式不是js為了執(zhí)行命令不報兼容的錯誤)
import fs from 'fs';
console.time('轉(zhuǎn)換耗時');
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('轉(zhuǎn)換耗時');
4.package.json命令改為:
"build": "vite build && node toFile.mjs",
npm run build 之后打開index.html文件:

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
elementui源碼學習之仿寫一個el-divider組件
這篇文章主要為大家介紹了elementui源碼學習之仿寫一個el-divider組件示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
Vue+thinkphp5.1+axios實現(xiàn)文件上傳
這篇文章主要為大家詳細介紹了Vue+thinkphp5.1+axios實現(xiàn)文件上傳,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-05-05
vue點擊右鍵出現(xiàn)自定義操作菜單實現(xiàn)代碼
這篇文章主要給大家介紹了關(guān)于vue點擊右鍵出現(xiàn)自定義操作菜單實現(xiàn)的相關(guān)資料,在網(wǎng)頁中我們也希望可以像桌面軟件一樣,點擊右鍵后出現(xiàn)操作菜單,對選中的數(shù)據(jù)項進行相應的操作,需要的朋友可以參考下2023-08-08

