Uncaught ReferenceError: Buffer is not defined

Total
0
Shares

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!


Solution

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")
        }
    },

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *