React Native 无法解析模块加密

3phpmpom  于 2023-01-27  发布在  React
关注(0)|答案(2)|浏览(218)

我尝试在我的React-Native Wallet应用中实现WalletConnect V1。但是,每当我使用以下导入时:

import WalletConnect from "@walletconnect/client";

出现以下错误:

Unable to resolve module crypto from /Users/<my-name>/<company-name>/<client-name>/<app-name>/node_modules/@walletconnect/randombytes/dist/cjs/node/index.js: crypto could not be found within the project or in these directories:
  node_modules

我尝试了一些解决方案,但是安装crypto-js和crypto-js@3.3.0都没有解决这个问题,我也已经在我的应用程序中安装了react-native-crypto。
任何帮助弄清楚我需要做什么来解决这个错误将是惊人的!

thigvfpy

thigvfpy1#

只需将自定义解析器添加到您的城域网配置

// metro.config.js
module.exports = {
  resolver: {
    extraNodeModules: {
      crypto: require('react-native-cyrpto'),
    },
  },
};

不幸的是,crypto依赖于其他nodejs软件包,如:net、tls、fs等。建议使用https://github.com/parshap/node-libs-react-native,它在react-native中对节点包进行多边填充
Docs
三硝基甲苯;

nom install node-libs-react-native

// metro.config.js
module.exports = {
  resolver: {
    extraNodeModules: require('node-libs-react-native'),
  },
};
wgxvkvu9

wgxvkvu92#

我设法解决这个问题,感谢这篇文章(https://github.com/parshap/node-libs-react-native/issues/23

yarn add react-native-get-random-values

const nodelibs = require("node-libs-react-native");

nodelibs.crypto = `${__dirname}/src/crypto.js`;

module.exports = {
  resolver: {
    extraNodeModules: nodelibs,
  },
};

然后创建了我自己的crypto.js文件

// src/crypto.js
'use strict'
import { Buffer } from 'buffer';
const { NativeModules } = require('react-native');

const randomBytes = (size) => {
  if (NativeModules.RNGetRandomValues) {
    return Buffer(NativeModules.RNGetRandomValues.getRandomBase64(size));
  } else {
    throw new Error('Native module not found')
  }
};

exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = randomBytes;

相关问题