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 packages and updated packages in .737s
/Users/Easy/Playground/lm1/node_modules/rn-nodeify/cmd.js:
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了……自行测试吧