【解决】vite 项目打包空后在 android 中白屏

1,188 阅读1分钟

一、原因

在使用 vue + vite 开发,测试时发现很多低版本的 android 手机浏览器出现白屏的现象,而ios机型基本上是好的,原因是主要原因是 vite 采用 es module打包,需要在服务器的环境下才能运行,下面给出解决方案:

二、解决方式

白屏的主要原因是加载文件加载不出来。分别安装 @vitejs/plugin-legacy 和 terser。 通过插件 @vitejs/plugin-legacy 来自动生成传统浏览器的 chunk 及与其相对应 ES 语言特性方面的 polyfill。兼容版的 chunk 只会在不支持原生 ESM 的浏览器中进行按需加载。
package.json 中依赖如下:

"@vitejs/plugin-legacy": "^1.8.2"

vite.config.js 中修改如下:

plugins: [
   legacy({
      targets: ['chrome 52'],
      additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      renderLegacyChunks: true,
      polyfills: [
        'es.symbol',
        'es.promise',
        'es.promise.finally',
        'es/map',
        'es/set',
        'es.array.filter',
        'es.array.for-each',
        'es.array.flat-map',
        'es.object.define-properties',
        'es.object.define-property',
        'es.object.get-own-property-descriptor',
        'es.object.get-own-property-descriptors',
        'es.object.keys',
        'es.object.to-string',
        'web.dom-collections.for-each',
        'esnext.global-this',
        'esnext.string.match-all'
      ]
   })
],

三、打包检验

查看打包出来的dist里的index.html可知,script的引入方式有两种,检测当前浏览器支持原生ESM时,加载 <script type="module">,而对于低版本的浏览器会加载<script nomodule>相应的js。

image.png

以上就是解决方法,亲测有效!