问题
在使用vue3和vite4+开发一个移动端H5,低版本的手机浏览器不支持加载,显示白屏。高版本的可以正常加载。原因是很多低版本浏览器并不支持原生ESM导入的方式
解决方案
默认情况下,Vite 的目标浏览器是指能够 支持原生 ESM script 标签 和 支持原生 ESM 动态导入 的。作为参考,Vite 使用这个 browserslist 作为查询标准:
Chrome >=87
Firefox >=78
Safari >=13
Edge >=88
1.vite.config.ts里 build.target 配置项 指定构建目标为 es2015
build: {
target: 'es2015',
},
2.先安装官方插件 @vitejs/plugin-legacy 来自动生成传统浏览器的 chunk 及与其相对应 ES 语言特性方面的 polyfill。兼容版的 chunk 只会在不支持原生 ESM 的浏览器中进行按需加载。
1.安装@vitejs/plugin-legacy
npm install @vitejs/plugin-legacy -D
注意:必须安装 Terser,因为旧版插件使用 Terser 进行缩小。
npm install terser -D
2.配置 vite.config.js
import { defineConfig } from 'vite';
import legacyPlugin from '@vitejs/plugin-legacy';
export default defineConfig({
plugins: [
// 浏览器兼容问题配置
legacyPlugin({
targets: ['defaults', 'not IE 11'],
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'
]
})
],
build: {
target: 'es2015',
minify: 'terser',
terserOptions: {
compress: {
// 生产环境时移除console
drop_console: true,
drop_debugger: true,
}
}
}
});
打包、运行到浏览器。