vite打包后的项目在有的浏览器上报错globalThis is not defined

  1. 安装依赖

@vitejs/plugin-legacy 2.x版本,需要vite3.x版本

yarn add @vitejs/plugin-legacy -D
  1. 修改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,
      }),
  ]
})
  1. 修改入口文件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>

资料

posted @ 2022-09-15 11:33  小菜菜爱吃菜  阅读(1735)  评论(0编辑  收藏  举报