Har*_*oli 10 global-variables node.js npm react-native
我正在尝试在我的 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());
}
},
};
Run Code Online (Sandbox Code Playgroud)
我的猜测是在加载此全局变量之前正在评估标准库,因此会引发错误。
eha*_*nom 11
我跑了npm install buffer,把它放在需要的文件的顶部Buffer:
global.Buffer = global.Buffer || require('buffer').Buffer
Run Code Online (Sandbox Code Playgroud)
在 TypeScript 中,我必须Buffer明确导入。
import { Buffer } from "buffer"
Run Code Online (Sandbox Code Playgroud)
我原以为编译器会抱怨Buffer在导入之前丢失和/或"source.organizeImports": true在保存文件时会删除该行,但两者都不是。
@ehacinom 的解决方案也有效。
回到这里留下一个解决方案,以防有人陷入困境。解决方案本质上是尝试在不同时间填充不同的包以更改加载顺序。
当 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:'
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16663 次 |
| 最近记录: |