Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: Buffer is not defined

Our application kept showing the error in the title. The problem is very likely related to Webpack 5 polyfill and after going through a couple of solutions:

  1. Setting fallback + install with npm
fallback: {
  "stream": require.resolve("stream-browserify"),
  "buffer": require.resolve("buffer/")
}
  1. Setting alias
alias: {
  "buffer": "buffer",
  "stream": "stream-browserify"
}

We are still seeing the dreadful error:

rfc6979.js:3 Uncaught ReferenceError: Buffer is not defined
    at Object.4142 (rfc6979.js:3)
    at r (bootstrap:19)
    at Object.5892 (js.js:4)
    at r (bootstrap:19)
    at Object.4090 (bip32.js:5)
    at r (bootstrap:19)
    at Object.7786 (index.js:3)
    at r (bootstrap:19)
    at Object.1649 (MnemonicKey.js:50)
    at r (bootstrap:19)

Our setup is vanilla NodeJS + TypeScript + Webpack for multi-target: node + browser. Any help would be great!

like image 318
whileone Avatar asked Aug 09 '21 06:08

whileone


People also ask

How do you fix ReferenceError require is not defined?

To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.

What is JavaScript buffer?

What is a buffer? A buffer is an area of memory. Most JavaScript developers are much less familiar with this concept, compared to programmers using a system programming language (like C, C++, or Go), which interact directly with memory every day.

What is buffer node JS?

Buffers in Node. js is used to perform operations on raw binary data. Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities, but the difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not be resizable.

Why can't I use buffer on client?

Checked on 1.3.2 and still can't use Buffer on client. If you install polyfill buffer package, you get the error: It appears you're using a module that is built in to node, but you installed it as a dependency which could cause problems. Please remove buffer before continuing.

Why is polyfill buffer package not working on node?

If you install polyfill buffer package, you get the error: It appears you're using a module that is built in to node, but you installed it as a dependency which could cause problems. Please remove buffer before continuing. This is why I have the patch that removes the check for node builtins.

Why can't I use buffer with Webpack?

In Webpack version 5, Webpack no longer automatically polyfill's Node.js API's if they are not natively supported anymore. The browser environment does not support Buffer natively, therefore we now need to add a third party Buffer package and point Node.js to it in the Webpack config.

How can I pass an encoding argument to buffer from?

Like toString (), you can pass an encoding argument to Buffer.from (). create object let dog = { name: "Sally", breed: "Border Collie", age: 3, bark: function () { alert ("Bark!


Video Answer


8 Answers

Answering my own question. Two things helped to resolve the issue:

  1. Adding plugins section with ProviderPlugin into webpack.config.js
const webpack = require('webpack');

module.exports = {
    // ...

    plugins: [
        // Work around for Buffer is undefined:
        // https://github.com/webpack/changelog-v5/issues/10
        new webpack.ProvidePlugin({
            Buffer: ['buffer', 'Buffer'],
        }),
        new webpack.ProvidePlugin({
            process: 'process/browser',
        }),
    ],

  1. Also add in resolve.fallback into webpack.config.js:
    resolve: {
        extensions: [ '.ts', '.js' ],
        fallback: {
            "stream": require.resolve("stream-browserify"),
            "buffer": require.resolve("buffer")
        }
    },

like image 78
whileone Avatar answered Oct 23 '22 07:10

whileone


Everyone who came here because of react-scripts (5.0.0) (@whileons answer is correct, this is only the configuration for react-scripts):

First, add these dependencies to your package.json:

"buffer": "^6.0.3",
"process": "^0.11.10",
"stream-browserify": "^3.0.0"
"react-app-rewired": "^2.2.1" --dev

Update your package.json scripts.

Before:

"scripts": {
    "debug": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

After

  "scripts": {
    "debug": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },

Create a file config-overrides.js in the root folder (NOT under src, in the same folder like your package.json) and paste the following code inside:

const webpack = require("webpack")

module.exports = function override(config, env) {
    //do stuff with the webpack config...
    config.resolve.fallback = {
        ...config.resolve.fallback,
        stream: require.resolve("stream-browserify"),
        buffer: require.resolve("buffer"),
    }
    config.resolve.extensions = [...config.resolve.extensions, ".ts", ".js"]
    config.plugins = [
        ...config.plugins,
        new webpack.ProvidePlugin({
            process: "process/browser",
            Buffer: ["buffer", "Buffer"],
        }),
    ]
    // console.log(config.resolve)
    // console.log(config.plugins)

    return config
}

Dont forget to delete node_modules and npm install it again.

like image 45
Paul Avatar answered Oct 23 '22 09:10

Paul


I've tried all the answers here to resolve this issue and nothing worked for me. What did work for me was putting the following in my polyfills.ts:

import { Buffer } from 'buffer';

// @ts-ignore
window.Buffer = Buffer;

and of course, npm install --save buffer

like image 32
parliament Avatar answered Oct 23 '22 09:10

parliament


What worked for me is the following:

First:

npm install --save buffer

Then:

// webpack.config.js
const webpack = require("webpack");

module.exports = {
  plugins: {
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    }),
    // ..
  }
  // ..
}
like image 30
Yulian Avatar answered Oct 23 '22 09:10

Yulian


You could also just install the following library: https://github.com/feross/buffer

yarn add buffer

like image 21
sirKris van Dela Avatar answered Oct 23 '22 07:10

sirKris van Dela


I've found a bug when I tried to use TonWebSDK with create-react-app and found a fix for that.

After project setup with npx create-react-app my-app I imported tonweb from 'tonweb' but faced an error Uncaught ReferenceError: Buffer is not defined.

I run npm run eject in order to modify the webpack config. I added Buffer support to the plugins of webpack with next lines:

 new webpack.ProvidePlugin({
          Buffer: ['buffer', 'Buffer'],
        })

And this worked for me.

like image 42
Wells Avatar answered Oct 23 '22 07:10

Wells


This worked for me

npm install --save buffer

Then in the file where I was using buffer

import { Buffer } from 'buffer';

I guess it wasn't installed, but my IDE already had type descriptions for it? Idk

like image 24
esafresa Avatar answered Oct 23 '22 09:10

esafresa


Additional detail for VueJS developers,
this answer worked and my vue.config.js file was like this.

const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack');

module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
  plugins: [
    // Work around for Buffer is undefined:
    // https://github.com/webpack/changelog-v5/issues/10
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    })
  
  ],
  resolve: {
    extensions: ['.ts', '.js'],
    fallback: {
      "stream": require.resolve("stream-browserify"),
      "buffer": require.resolve("buffer")
    }
  },
 }
})

I deleted my node_modules folder and ran npm install again.

like image 22
Harshadeva Priyankara Bandara Avatar answered Oct 23 '22 07:10

Harshadeva Priyankara Bandara