Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uncaught ReferenceError: Buffer is not defined #14202

Closed
idoall opened this issue Jun 21, 2022 · 10 comments
Closed

Uncaught ReferenceError: Buffer is not defined #14202

idoall opened this issue Jun 21, 2022 · 10 comments

Comments

@idoall
Copy link

idoall commented Jun 21, 2022

Environment

Nuxt CLI v3.0.0-rc.4 00:36:31
RootDir: /nuxt3-app 00:36:33
Nuxt project info: 00:36:33


  • Operating System: Darwin
  • Node Version: v16.15.1
  • Nuxt Version: 3.0.0-rc.4
  • Package Manager: yarn@1.22.19
  • Builder: vite
  • User Config: alias, publicRuntimeConfig, srcDir, dir, css, buildModules, meta, generate, ssr, vite
  • Runtime Modules: -
  • Build Modules: @vueuse/nuxt@8.6.0, @pinia/nuxt@0.1.9

👉 Report an issue: https://github.com/nuxt/framework/issues/new 00:36:33

👉 Suggest an improvement: https://github.com/nuxt/framework/discussions/new

👉 Read documentation: https://v3.nuxtjs.org

Reproduction

import {
Keypair
} from '@solana/web3.js';

Describe the bug

When using @solana/web3.js, issues such as global undefined have been resolved, and it works fine in dev mode.
After using yarn build, in yarn preview, it prompts an error:Uncaught ReferenceError: Buffer is not defined

Additional context

No response

Logs

No response

@danielroe
Copy link
Member

Would you provide a reproduction? 🙏

@idoall
Copy link
Author

idoall commented Jun 22, 2022

yarn add bip39 bs58 ethers @solana/web3.js ed25519-hd-key -D

test.vue

<script setup>
import { onMounted } from 'vue'
import {
  generateMnemonic,
  mnemonicToSeedSync
} from 'bip39';
import * as bs58 from "bs58";
import {
  ethers
} from 'ethers';
import {
  Keypair
} from '@solana/web3.js';
import {
  derivePath
} from "ed25519-hd-key";


onMounted(() => {

for (var i = 0; i < 10; i++) {
      const generatedMnemonic = generateMnemonic();
      const seed = mnemonicToSeedSync(generatedMnemonic).slice(0, 32);
      const path = `m/44'/501'/${parseInt(10*Math.random())}'/0'`;
      const keypair = Keypair.fromSeed(derivePath(path, seed.toString("hex")).key);
      console.log(keypair);
      console.log(`sol - ${i} - public key address: ${keypair.publicKey.toBase58()}`);
      console.log(`sol - ${i} - Mnemonic: ${generatedMnemonic}`);
      console.log(`sol - ${i} - path: ${path}`);
      console.log(`sol - ${i} - private key(raw): ${keypair.secretKey}`);
      console.log(`sol - ${i} - private key(bs58): ${bs58.encode(keypair.secretKey)}`);
    }

})

</script>
<template>
<div>
    this is a Test page
</div>
</template>

nuxt.config.ts

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'

export default defineNuxtConfig({
...
...
vite: {
    logLevel: 'info',
    // plugins: [eslintPlugin()],
    optimizeDeps: {
      esbuildOptions: {
        define: {
          global: 'globalThis'  // fix nuxt3 global
        },
        plugins: [
          NodeGlobalsPolyfillPlugin({
            process: true,  // fix nuxt3 process
            buffer: true
          }),
          NodeModulesPolyfillPlugin()
        ]
      }
    },
  }
}

There are no problems when yarn dev and no errors when yarn build.
Just prompt when yarn preview:Uncaught ReferenceError: Buffer is not defined

@shymarrai
Copy link

shymarrai commented Jun 30, 2022

for me what worked was:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import inject from '@rollup/plugin-inject'

export default defineConfig({
	plugins: [vue()],
	resolve: {
		alias: {
			'@': path.resolve(__dirname, 'src'),
		}
	},
	build: {
		rollupOptions: {
			plugins: [inject({ Buffer: ['buffer', 'Buffer'] })],
		},
	},
})

reply to this comment:

vitejs/vite#2785 (reply in thread)

@andysay
Copy link

andysay commented Jul 11, 2022

same problem..

@WhiteR4bbitt
Copy link

WhiteR4bbitt commented Sep 8, 2022

I had an issue with Buffer in a few situations (Vite/Vue, Nuxt) and the above has worked before, but using Nuxt3 (rc9) I could not get past the whole Buffer not defined there or it duplicating itself causing another error..

This is what I have that got me using a web3 npm package that was causing the issue to begin with (I will dig into the package later and see how its using Buffer, but for now this is what I did)

./nuxt.config.ts

import { defineNuxtConfig } from 'nuxt'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
  srcDir: './src',
  ssr: false,
  vite: {
    resolve: {
      alias: {
        stream: 'stream-browserify',
        // process: 'process/browser',
        // util: 'util'
      }
    },
    optimizeDeps: {
      esbuildOptions: {
        define: {
          global: 'globalThis',
        },
        plugins: [
          NodeGlobalsPolyfillPlugin()
        ],
      },
    }
  }
})

Created a new file ./src/server/plugins/render.ts

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('render:html', (html, { event }) => {
    html.head.push('<script>var global = global || window</script>')
    html.head.push(`<script type="module">
      import { Buffer as Buffer } from '/Buffer.js'
      
      window.Buffer = Buffer || []
      window.process = window.process || { env: {} }
    </script>`)
  })
})

I added global here as well because the Buffer injection was complaining about global being undefined, so just another shortcut.. process was complaining during the production build about an env key missing.

I had seen the nitro:html hook from this issue: #14172

Also I put Buffer.js in my public folder since its importing a local file above, you can find it online or I pasted it here: https://gist.github.com/WhiteR4bbitt/dcdf6d8ceae07df414225a63d118f300

There are probably other ways to include this file, but things just didn't want to work.. You may also need more alias' if it complains about other missing dependencies. (commented out above)

@madebyfabian
Copy link
Sponsor Collaborator

Hey there, it's always great to add a real reproduction link like described in the docs. Anyways I've created one with the latest Nuxt Version (https://stackblitz.com/edit/github-7fvdyh?file=nuxt.config.ts,package.json,app.vue) and everything works like a charm configuring it in the right way. Since this is not directly a nuxt issue and more an issue with the modules you are using and they way you configure them in vite, I'd suggest to close this.

@danielroe danielroe closed this as not planned Won't fix, can't repro, duplicate, stale Mar 14, 2023
@carbdias
Copy link

carbdias commented Jan 9, 2024

I have the same problem with Buffer, using it inside a plugin (Buffer.from(..)) gives : Buffer is not defined
Which is the recommended solution ?

@falasyam
Copy link

Try installing buffer from npm and import it into your file that contains buffer.

Example:

import { Buffer } from "buffer";

@carbdias
Copy link

Thank you,
It works.

@transtone
Copy link

#25016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

9 participants