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了……自行測試吧