移动端如何加载vite导出dist包
# vite导出dist包不能直接在移动端webView进行直接打开引用,需要特殊处理,步骤如下:
- 1, 安装 vitejs/plugin-legacy 插件, 打包导出dist;
- 2,对于安卓端可以直接使用loadUrl 的webview 原生方法来直接加载内容; 对于iOS端需要dist包做一些删减处理,dist包中的index.html做出一些删减:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="./vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>Vite + Vue</title>
<!-- 删除整行 -->
<script type="module" crossorigin src="./assets/index-yodXH7xc.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-9ISEl0BN.css">
<!-- 删除整行 -->
<script type="module">import.meta.url;import("_").catch(()=>1);(async function*(){})().next();if(location.protocol!="file:"){window.__vite_is_modern_browser=true}</script>
<script type="module">!function(){if(window.__vite_is_modern_browser)return;console.warn("vite: loading legacy chunks, syntax error above and the same error below should be ignored");var e=document.getElementById("vite-legacy-polyfill"),n=document.createElement("script");n.src=e.src,n.onload=function(){System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))},document.body.appendChild(n)}();</script>
</head>
<body>
<div id="app"></div>
<!-- 删除整行 -->
<script nomodule>!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();</script>
<!-- 删除 nomodule 关键字-->
<script nomodule crossorigin id="vite-legacy-polyfill" src="./assets/polyfills-legacy-1emxtkzh.js"></script>
<!--1, 删除 nomodule 关键字 2,data-src 改为src 3,System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src')) 删除-->
<script nomodule crossorigin id="vite-legacy-entry" data-src="./assets/index-legacy-3BuIREnp.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
iOS 端代码
// 加载bundle的html文件,并且添加路由
if let htmlPath = Bundle.main.path(forResource: "dist/index", ofType: "html") {
let url = URL(fileURLWithPath: htmlPath)
// 假设你的Vue app使用哈希模式进行路由,把路由添加在'#'后面。
guard let newUrl = URL(string: self.type.allUrl, relativeTo: url) else { return }
// 使用loadFileURL允许读取本地文件
self.wkWeb.loadFileURL(newUrl, allowingReadAccessTo: newUrl)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
上次更新: 2024/05/07, 09:38:21