webview加载vue3报错_vite打包esmodule文件无法加载_legacy如何使用
2025-11-01 17:49:52
我们使用vite打包vue3时,不做处理会让app加载webview时无法正常加载。下面会列出处理方法让file能正常加载vite打包的vue3单页面
2232
我们使用app的webview加载vite打包的vue3静态文件时,会遇到无法找到文件或者文件跨域的问题。最根本的原因是app的webview加载file文件,不能加载esmodule的文件。 更改app端是比较复杂的,所以采用更改vite打包的静态文件形式。
操作步骤
安装vitejs/plugin-legacy插件
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加载静态文件
能正常访问静态文件即可
注意事项
webview加载本地单页面时,最好采用hash路由模式
参考文档:https://www.jianshu.com/p/14cce9ff60c2
