我们使用app的webview加载vite打包的vue3静态文件时,会遇到无法找到文件或者文件跨域的问题。最根本的原因是app的webview加载file文件,不能加载esmodule的文件。 更改app端是比较复杂的,所以采用更改vite打包的静态文件形式。
npm i @vitejs/plugin-legacy -D
vite.config.js
import { defineConfig } from 'vite';
import legacy from '@vitejs/plugin-legacy';
export default defineConfig({
plugins: [
legacy({
targets: ['defaults', 'not IE 11']
})
]
})
新增 bin/htmlFormat.js
const fs = require('fs');
const htmlPath = './dist/index.html'; // 打包后的html文件路径
const htmlText = fs.readFileSync(htmlPath, 'utf8');
const htmlArr = htmlText.match(/.*
/g) || [];
let result = '';
htmlArr.forEach((v) => {
v = v
.replace(/script ?nomodules?/g, 'script ')
.replace(/s?crossorigins?/g, ' ')
.replace(/<link rel="modulepreload" href="[^"]+.js">/g, '')
.replace("System.import(document.getElementById('vite-legacy-entry').getAttribute('src'))", '')
.replace(/data-src/g, 'src');
if (!v.includes(`script type="module"`)) {
result += v;
}
});
fs.writeFileSync(htmlPath, result, 'utf8');
npm run build npm run htmlFormat
能正常访问静态文件即可
webview加载本地单页面时,最好采用hash路由模式
参考文档:https://www.jianshu.com/p/14cce9ff60c2