Closed michalbujalski closed 10 months ago
@michalbujalski Have you tried adding the rollup-plugin-node-polyfills
plugin to the rollupOptions
?
import nodePolyfills from "rollup-plugin-node-polyfills";
export default defineConfig({
// add the following to the rest of your config:
build: {
rollupOptions: {
plugins: [ nodePolyfills() as any],
}
}
})
Yes, I got the same result
@michalbujalski Are you getting that error after running yarn preview
? Can you show what your config looks like for the optimizeDeps
option? You could also try changing your definition of global
to globalThis
:
define: {
global: "globalThis",
},
Also, if you see any errors in the dev tools console about require
, you might need to add the following to your build
option:
commonjsOptions: {
transformMixedEsModules: true,
},
any update on a fix
I ran into a similar set of issues with a Vite+React application. A local build worked as expected but the same build deployed to Netlify would throw the following errors in the Chrome DevTools console:
Uncaught ReferenceError: global is not defined
Uncaught ReferenceError: require is not defined
Uncaught ReferenceError: Buffer is not defined
Setting the transformMixedEsModules
field to true
and adding global node polyfills fixed these issues:
/* vite.config.ts */
import { nodePolyfills } from "vite-plugin-node-polyfills";
/* ... other config ... */
export default defineConfig({
/* ... other config ... */
build: {
commonjsOptions: {
transformMixedEsModules: true,
},
},
plugins: [
nodePolyfills({
globals: {
Buffer: true,
global: true,
process: true,
},
}),
]
})
transformMixedEsModules: true
enables mixed module transformations. This is useful for scenarios where modules include a mix of ES import
statements and CommonJS require
statements. Setting transformMixedEsModules
to true
transforms require
statements to import
statements (and vice versa for false
). This is useful for bundling hashconnect
since the ES esm/hashconnect.js
file uses a CommonJS 'require' statement to import buffer
: global.Buffer = global.Buffer || require('buffer').Buffer;
.
The node polyfills should fix the errors related to the 'not defined' global variables.
I have vite+React setup. Everything works fine in development enviroment but when I run
yarn build
I get the following error:I've added a workaround to
vite.config.ts
: