找不到变量:缓冲区

新手上路,请多包涵

我正在尝试在我的 react-native 应用程序中使用节点模块,并且在这里采用 ReactNativify 方法。

我现在一切都准备好了,我可以很好地加载加密包。但是,当我添加 eth-lightwallet 时,事情变得越来越奇怪。

自从我添加了那个包之后,npm 就没有安装任何依赖项。这意味着我必须手动添加它们。每次我安装与 eth-lightwallet 相关的依赖项时,都会卸载该模块。尽管乏味且烦人,但我希望它可以阐明我当前的问题。

现在我遇到了一个 Can't find variable: Buffer 它被扔在标准库的 util 文件夹中。我查看了代码,它正在从全局命名空间访问 Buffer。事情是,我正在将 Buffer 导入全局命名空间。这是我的 global.js

 // Inject node globals into React Native global scope.
global.Buffer = require('buffer').Buffer;
global.process = require('process');
global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production';

// Needed so that 'stream-http' chooses the right default protocol.
global.location = {
    protocol: 'file:',
};

// Don't do this in production. You're going to want to patch in
// https://github.com/mvayngrib/react-native-randombytes or similar.
global.crypto = {
    getRandomValues(byteArray) {
        for (let i = 0; i < byteArray.length; i++) {
            byteArray[i] = Math.floor(256 * Math.random());
        }
    },
};

我的猜测是在加载这个全局变量之前正在评估标准库,因此会引发错误。

原文由 arshbot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 785
2 个回答

回到这个问题上留下一个解决方案,以防有人被困在这个问题上。解决方案基本上是尝试在不同的时间在不同的包中填充以更改加载顺序。

当 TYPED_ARRAY_SUPPORT 被区别对待并且 Buffer 更加依赖它时,我们尝试返回到不同的版本。在旧版本上,我们尝试了很多不同的东西,最终放弃并通过将缓冲区更新到最新版本来回溯,最后一切正常。

我的意思是我们不确定我们是如何修复它的,但它是通过随机更改加载顺序直到我们幸运的。我知道,这不是一个好的答案,但我可以为这个问题提供最好的答案。

这是我们的 global.js 最后的样子

// Inject node globals into React Native global scope.
// Required for crypto functionality for bitcoinjs-lib, web3, etc.

global.Buffer = require('buffer').Buffer;
//global.Buffer.TYPED_ARRAY_SUPPORT = false;

global.process = require('process');
global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production';

var getRandomValues = function(byteArray) {
  var bytes = crypto.rng.randomBytes(byteArray.length);
  for (let i = 0; i < byteArray.length; i++) {
    byteArray[i] = bytes[i];
  }
};
// "But Zach, aren't you just doing the same thing twice?"
// Yes. Initializing the crypto-browserify module eventually requires
// crypto.getRandomValues to exist, so we must add it here once.
// However, crypto-browserify does not support getRandomValues, so we
// must re-add it after loading the module.
global.crypto = { getRandomValues };
global.crypto.rng = require('react-native-randombytes');
global.crypto = require('crypto');
global.crypto.getRandomValues = getRandomValues;
global.crypto.rng = require('react-native-randombytes');
crypto.rng.seedSJCL();

// Needed so that 'stream-http' chooses the right default protocol.
global.location = {
  protocol: 'file:'
};

原文由 arshbot 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 TypeScript 中,我必须明确导入 Buffer

 import { Buffer } from "buffer";

我原以为编译器会抱怨 Buffer 在导入之前丢失和/或 "source.organizeImports": true 在保存文件时会删除该行,但两者都不是真的。

@ehacinom 的解决方案也有效。

原文由 Jan Aagaard 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏