Hashpack / hashconnect

Hashconnect library, readme in progress
BSD Zero Clause License
46 stars 38 forks source link

Problem with `global` in prod build vite + React #139

Closed michalbujalski closed 10 months ago

michalbujalski commented 2 years ago

I have vite+React setup. Everything works fine in development enviroment but when I run yarn build I get the following error:

image

I've added a workaround to vite.config.ts:

export default defineConfig({
  plugins: [react()],
  define: {
    global: {}
  },
...
johnrdoty92 commented 2 years 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],
    }
  }
})
michalbujalski commented 2 years ago

Yes, I got the same result

johnrdoty92 commented 2 years ago

@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,
},
bdxndev commented 1 year ago

any update on a fix

damiano-melcarne-lab49 commented 1 year ago

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.