解決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等關鍵詞,省的每次得手動刪除)toFile.mjs
創(chuàng)建 toFiles.mjs (為啥格式不是js為了執(zhí)行命令不報兼容的錯誤)
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文件:
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解使用VUE搭建后臺管理系統(tǒng)(vue-cli更新至3.0)
這篇文章主要介紹了詳解使用VUE搭建后臺管理系統(tǒng)(vue-cli更新至3.0),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08vue如何修改data中的obj數(shù)據(jù)的屬性
這篇文章主要介紹了vue如何修改data中的obj數(shù)據(jù)的屬性,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08Vue?props傳入function時的this指向問題解讀
這篇文章主要介紹了Vue?props傳入function時的this指向問題解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01