zoukankan      html  css  js  c++  java
  • 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了……自行测试吧

  • 相关阅读:
    第28月第23天 lineFragmentPadding
    第28月第22天 iOS动态库
    第28月第21天 记事本Unicode 游戏编程中的人工智能技术
    第28月第11天 vim -b
    第28月第10天 iOS动态库
    第28月第8天
    第28月第7天 本地摄像头方向
    第28月第5天 uibutton交换方法
    第28月第4天 __bridge_transfer
    python __getattr__ __setattr__
  • 原文地址:https://www.cnblogs.com/qiyecao/p/9689223.html
Copyright © 2011-2022 走看看