ViteJS打包向下兼容低版本浏览器
JyLie 2022-08-23 ViteJS
# 前言
始初开发移动端新项目,用上 vue3 和 ViteJS 即可一劳而永逸,然而在测试时发现某些低版本(一般指 Android 7 及以下版本)的安卓手机浏览器出现白屏的现象,而 ios 机型基本上是好的。在调试后发现在低版本浏览器并不支持原生 ESM 导入的方式,于是乎有了这篇文章做记录。
# 兼容原生 ESM 的浏览器
默认情况下,Vite 的目标浏览器是指能够 支持原生 ESM script 标签 和 支持原生 ESM 动态导入 的。
作为参考,Vite 使用这个 browserslist 作为查询标准:
defaults and supports es6-module and supports es6-module-dynamic-import, not opera > 0, not samsung > 0, not and_qq > 0
Chrome >=87
Firefox >=78
Safari >=13
Edge >=88
1
2
3
4
5
6
2
3
4
5
6
# 解决方法
在
vite.config.ts
文件的build.target
配置项 指定构建目标为es2015
安装插件
@vitejs/plugin-legacy
。
pnpm add @vitejs/plugin-legacy -D
1
插件会自动生成传统浏览器的 chunk 及与其相对应 ES 语言特性方面的 polyfill。兼容版的 chunk 只会在不支持原生 ESM 的浏览器中进行按需加载。
# 最终效果
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ViteLegacy from '@vitejs/plugin-legacy'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
ViteLegacy({
targets: ['chrome 52'],
additionalLegacyPolyfills: ['regenerator-runtime/runtime'] /* 兼容IE11 */,
renderLegacyChunks: true,
// polyfills: [
// 'es.symbol',
// 'es.array.concat',
// 'es.array.filter',
// 'es.array.flat',
// 'es.array.flat-map',
// 'es.promise',
// 'es.promise.finally',
// 'es/map',
// 'es/set',
// 'es.array.for-each',
// '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'
// ]
}
],
build: {
target: 'es2015'
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40