捕获到未定义的引用错误:Buffer未定义。

92

我们的应用程序一直显示标题中的错误。问题很可能与Webpack 5 polyfill有关,经过尝试了几种解决方案后:

  1. 设置回退+使用npm安装
fallback: {
  "stream": require.resolve("stream-browserify"),
  "buffer": require.resolve("buffer/")
}
  1. 设置别名
alias: {
  "buffer": "buffer",
  "stream": "stream-browserify"
}
我们仍然看到可怕的错误:

我们仍然看到可怕的错误:

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)

我们的设置是使用纯净的NodeJS + TypeScript + Webpack进行多目标(node和browser)构建。任何帮助都将是巨大的!

14个回答

97

回答自己的问题。两件事帮助解决了这个问题:

  1. 在webpack.config.js中添加包含ProviderPlugin的plugins部分
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. 在webpack.config.js中添加resolve.fallback:
    resolve: {
        extensions: [ '.ts', '.js' ],
        fallback: {
            "stream": require.resolve("stream-browserify"),
            "buffer": require.resolve("buffer")
        }
    },


3
我正在使用react-scripts 5,但这个解决方案对我不起作用。我尝试使用react-app-rewired按照说明添加config-overrides.js。但是应用程序仍然找不到缓冲区。 - tonisives
3
注意 @tonisives,在进行此更改后,您可能需要清除缓存—— rm -fr node_modules/.cache - jfrumar
1
谢谢!我通过添加 yarn add process 成功解决了它。这是我的完整概述 https://github.com/terra-money/terra.js/issues/223 - tonisives
你好 @whileone -- 这对我的使用情况有所帮助,但是你知道为什么在 Webpack 4 中不需要这个,而在 Webpack 5 中需要吗?修复这些破坏性变化真是一场噩梦。 - nsun

63

我尝试了所有这里的答案来解决这个问题,但对我来说都没有用。对我有用的是在我的polyfills.ts中加入以下内容:

import { Buffer } from 'buffer';

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

当然,npm install --save buffer


1
太棒了!这可以独立于所使用的框架运行。 - Florian Metzger-Noel
4
我在单个文件中使用了Buffer。只需导入并在该单个文件中设置window.Buffer即可解决问题,无需创建polyfills.ts文件。 - Gustavo Garcia
如果您在使用React和Vite时没有任何polyfill文件,请将其添加到应用程序的根目录中的某个位置。例如,在App.jsx或main.jsx中添加。 - undefined

41

每个因为react-scripts (5.0.0)而来到这里的人(@whileons的回答是正确的,但这仅是针对react-scripts的配置):

首先,在你的package.json中添加以下依赖项:

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

更新您的package.json脚本。

Before:

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

之后

  "scripts": {
    "debug": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
在根目录下创建一个名为config-overrides.js的文件(不要在src下创建,在和package.json同级的文件夹中创建),并将以下代码粘贴到文件中:
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
}

不要忘记删除 node_modules 文件夹并重新执行 npm install


2
这对我来说似乎有效。只是想指出文件名需要是 config-overrides.js(复数形式)。 - Adam M Thompson
2
非常有帮助,我忘记了遵循最后一行“删除node_modules”。但最终我删除了node_modules并重新安装以使事情运行。 - Learner
谢谢。有一件事情让我困惑 - 我正在使用 "yarn start" - 而在您的版本中,您把 "debug" 作为启动脚本的名称 - 因此 "start" 没有起作用。我将它改为 "start",一切都按预期工作了。只是提醒其他人也可能陷入同样的问题。 - Korimako

14
这对我有用。
npm install --save buffer

然后,在我使用缓冲区的文件中

import { Buffer } from 'buffer';

我猜测它并没有被安装,但是我的IDE已经有了它的类型描述?我不知道。


有没有一种全局安装的方法?就像你不再需要 import React 来使用 React 功能一样。我不明白为什么我们不再需要 import React,但如果我们可以使用相同的技术来处理 Buffer,我就不需要导入它了 - 而且我需要将其导入到我的 node_modules/mqtt-packet/constants 文件中,以使我的 mqtt-react-hooks 包可用。 - NULL pointer

11
以下是我的做法:
首先:
npm install --save buffer

然后:

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

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    }),
    // ..
  ]
  // ..
}

6

我曾遇到相同的错误,以下是我解决问题的方法。

首先:

npm install --save buffer

然后:
将这段代码添加到我的app.tsx文件中。
window.Buffer = window.Buffer || require("buffer").Buffer;

4

针对VueJS开发者,以下是更为详细的信息。
这个答案有效,我的vue.config.js文件如下。

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

我删除了 node_modules 文件夹并重新运行了 npm install


类型错误:defineConfig 不是一个函数。 - Abdul Manan
你使用的是哪个版本的webpack、vue和npm?vue 3与webpack 5.88.2以及npm 9.8.1在webpack\lib\compilation.js\中引发了一个TypeError错误。 - undefined

3

2

虽然大家都建议安装 polyfill,但是在 NodeJS 中有一种本地方式可以实现这一点,详见他们的文档

import { Buffer } from 'node:buffer'

如果您正在使用NodeJs,包括Webpack,而不是在浏览器中使用,则这是首选解决方案。

1

我尝试使用TonWebSDK和create-react-app时发现了一个错误,并找到了解决方法。

在使用npx create-react-app my-app设置项目后,我导入了tonweb from 'tonweb',但遇到了未捕获的引用错误:Buffer未定义的错误。

我运行npm run eject以修改webpack配置。 我将下面的代码添加到webpack的plugins中,以添加对Buffer的支持:

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

这对我有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接