globalThis is not defined #7915
-
I'm aware this isn't a Vite issue, but I'm looking for a Vite-way to fix this. On older browsers our React app breaks with the error:
The easy fix is to add the following to the
However it feels like a bit of a duct-taped fix, is there a way to fix this from |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I also have this problem, because there is no In vite, it can be configured at @vitejs/plugin-legacy: // vite.config.js
import legacy from '@vitejs/plugin-legacy';
export default defineConfig({
// For production build environments only
build: {
target: 'es2015',
},
plugins: [
// For production build environments only
legacy({
targets: ['chrome >= 64', 'edge >= 79', 'safari >= 11.1', 'firefox >= 67'],
ignoreBrowserslistConfig: true,
renderLegacyChunks: false,
/**
* Polyfills required by modern browsers
*
* Since some low-version modern browsers do not support the new syntax
* You need to load polyfills corresponding to the syntax to be compatible
* At build, all required polyfills are packaged according to the target browser version range
* But when the page is accessed, only the required part is loaded depending on the browser version
*
* Two configuration methods:
*
* 1. true
* - Automatically load all required polyfills based on the target browser version range
* - Demerit: will introduce polyfills that are not needed by modern browsers in higher versions,
* as well as more aggressive polyfills.
*
* 2、string[]
* - Add low-version browser polyfills as needed
* - Demerit: It needs to be added manually, which is inflexible;
* it will be discovered after the production is deployed, resulting in production failure! ! !
*/
modernPolyfills: ['es/global-this'],
// or
// modernPolyfills: true,
}),
],
}); |
Beta Was this translation helpful? Give feedback.
-
is it mandatory to indicate those targets? could them be lower? |
Beta Was this translation helpful? Give feedback.
I also have this problem, because there is no
globalThis
variable in lower version browsers, and the corresponding polyfill needs to be introduced:https://github.com/zloirock/core-js#ecmascript-globalthis
In vite, it can be configured at @vitejs/plugin-legacy: