React Native 调用 Web3(1.x) 的正确姿势

1 创建项目

react-native init lm1
cd lm1

2 安装依赖包

yarn add node-libs-browser

3 创建 rn-cli.config.js 脚本

const extraNodeModules = require('node-libs-browser');

module.exports = {
  extraNodeModules,
};

4 创建 global.js ,引入公用包

global.Buffer = require('buffer').Buffer;
global.process = require('process');

if (typeof btoa === 'undefined') {
    global.btoa = function (str) {
      return new Buffer(str, 'binary').toString('base64');
    };
  }
  
  if (typeof atob === 'undefined') {
    global.atob = function (b64Encoded) {
      return new Buffer(b64Encoded, 'base64').toString('binary');
    };
  }

5 在 app.js 中引入 global

import './global';

6 安装 babel-preset-es2015

yarn add --dev babel-cli babel-preset-es2015

安装加密用包

yarn add react-native-crypto react-native-randombytes

安装兼容工具

yarn add --dev tradle/rn-nodeify

link

react-native link 

生成兼容js

./node_modules/.bin/rn-nodeify --hack --install

然后在 App.js 中引入

import './shim.js'
import crypto from 'crypto'

7 安装 web3

yarn add web3

8  调用 web3

import Web3 from 'web3';


...

componentWillMount() {
    const web3 = new Web3(
      new Web3.providers.HttpProvider('https://mainnet.infura.io/')
    );
  
    web3.eth.getBlock('latest').then(console.log)
  }

9 启动日志

react-native log-android

10 运行应用

react-native run-android

如果报错

contributors, removed 95 packages and updated 1064 packages in 156.737s
/Users/Easy/Playground/lm1/node_modules/rn-nodeify/cmd.js:74
      if (err) throw err
               ^

Error: ENOENT: no such file or directory, open '/Users/Easy/Playground/lm1/node_modules/rn-nodeify/shim.js'
报错以后怎么办呢?
react-native link

然后 重新装 rn-nodefiy

yarn add --dev tradle/rn-nodeify

再运行

./node_modules/.bin/rn-nodeify --hack --install

这一次终于可以在根目录下成功生成 shim.js 了。

PS: windows下还要装 python 和 vcbuild.exe 一堆东西…… 我电脑装不下VS了……自行测试吧

转载于:https://www.cnblogs.com/qiyecao/p/9689223.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值