一、问题描述
vite打包的页面在低版本浏览器上会展示空白,并报错。
Uncaught SyntaxError: Unexpected token ?
二、解决方案
步骤一: vite.config.ts里 build.target 配置项 指定构建目标为 es2015
步骤二: 通过插件 @vitejs/plugin-legacy 来自动生成传统浏览器的 chunk 及与其相对应 ES 语言特性方面的 polyfill。兼容版的 chunk 只会在不支持原生 ESM 的浏览器中进行按需加载。
1、安装@vitejs/plugin-legacy
yarn add @vitejs/plugin-legacy -D
import { defineConfig } from 'vite';
import path from 'node:path';
const resolve = filepath => path.resolve(__dirname, filepath);
import reactRefresh from '@vitejs/plugin-react-refresh';
import legacy from '@vitejs/plugin-legacy';
export default defineConfig(({ mode }) => {
return {
...
build: {
...
target: 'es2015',
},
plugins: [
reactRefresh(),
legacy({
targets: ['ie >= 11', 'chrome <= 60'],
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'
]
})
],
};
});
注意:
1、注意配置需要兼容的浏览器范围
targets: ['ie >= 11', 'chrome <= 60'],
2、打包构建项目时可能会遇到打包失败的问题
[vite:terser] terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.
把缺少的项安装好就可以打包了
yarn add terser