vite打包后的项目在有的浏览器上报错globalThis is not defined
- 安装依赖
@vitejs/plugin-legacy 2.x版本,需要vite3.x版本
yarn add @vitejs/plugin-legacy -D
- 修改vite.config.js相配置
import legacy from '@vitejs/plugin-legacy';
export default defineConfig({
build: {
target: 'es2015',
},
plugins: [
legacy({
targets: ['Chrome 63'],
additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
modernPolyfills: true,
}),
]
})
- 修改入口文件mian.js和index.html
// main.js
if (typeof window.global === 'undefined') {
window.global = window;
}
// index.html
<script>
var global = globalThis;
</script>
<script>
this.globalThis || (this.globalThis = this);
</script>