UWP(Build14393)WebView加载React SPA遇空白屏与SCRIPT5022错误求助
解决UWP Build14393 WebView加载Vite React应用的SCRIPT5022错误
问题根源
UWP Build14393自带的WebView基于IE11引擎,不支持ES模块(<script type="module">),也无法解析Vite默认输出的ES6+语法,这就是出现空白页和SCRIPT5022: Expected '('错误的原因。
解决方案
1. 配置Vite兼容IE11
首先安装Vite的IE兼容插件:
npm install @vitejs/plugin-legacy --save-dev
修改vite.config.ts,添加插件配置:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import legacy from '@vitejs/plugin-legacy' export default defineConfig({ plugins: [ react(), legacy({ targets: ['ie11'], additionalLegacyPolyfills: ['regenerator-runtime/runtime'], renderLegacyChunks: true, polyfills: [ 'es.symbol', 'es.array.filter', 'es.promise', 'es.object.assign', 'es.array.includes' ] }) ] })
2. 调整TypeScript编译目标
修改tsconfig.json,将编译目标设为ES5,确保输出代码兼容IE11:
{ "compilerOptions": { "target": "ES5", // 保留其他原有配置 } }
3. 修改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" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Vite + React + TS</title> </head> <body> <div id="root"></div> <script> // 适配IE11的全局变量 window.global = window; if (typeof globalThis === 'undefined') { window.globalThis = window; } </script> <!-- 无需手动引入module脚本,legacy插件会自动生成兼容脚本 --> </body> </html>
4. 重新构建部署
执行构建命令生成兼容代码:
npm run build
将构建后的dist目录部署,再用UWP Build14393的WebView加载即可。
关键说明
- IE11完全不支持ES模块,移除
type="module"是解决加载失败的核心 - legacy插件会自动转译ES6+代码为ES5,并添加必要的polyfill,填补IE11的API缺失
内容的提问来源于stack exchange,提问作者Ankush Butole
相关产品推荐
相关产品推荐

