由于react native对nodejs的支持并不是很完善,当你
react-native init project
cd project
yarn add @polkadot/api
之后用以下代码测试
import {WsProvider,ApiPromise} from '@polkadot/api'
const App = () => {
const usingHermes = typeof HermesInternal === 'object' && HermesInternal !== null;
getData();
return (
<>...省略
)}
async function getData(){
const WS_PROVIDER = 'wss://dev-node.substrate.dev:9944'
const wsProvider = new WsProvider(WS_PROVIDER)
const api = await ApiPromise.create({provider: wsProvider})
console.log(api.genesisHash.toHex())
}
会发现有各种报错
Loading dependency graph, done.
error: bundling failed: Error: Unable to resolve module `util` from `node_modules/@polkadot/util/polyfill/textDecoder.js`: util could not be found within the project.
解决方案
来源 https://github.com/hashpire/polkadotjsWithReactNative
1.安装polkadot-js相关依赖
yarn add @polkadot/api @polkadot/keyring
2.安装Node core modules for React Native
yarn add node-libs-react-native vm-browserify bs58
3.编辑项目根目录下的metro.config.js
const nodeLibs = require("node-libs-react-native");
nodeLibs.bs58 = require.resolve("bs58");
nodeLibs.vm = require.resolve("vm-browserify");
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false
}
})
},
resolver: {
extraNodeModules: nodeLibs
}
};
4. 编辑项目根目录下的index.js
, 在引入App.js前添加
import 'node-libs-react-native/globals';
5.使用 react-native-randombytes
yarn add react-native-randombytes
cd ios
pod install
cd ..
6. 编辑package.json的script,加上NODE_OPTIONS=--max_old_space_size=8192,避免出现Allocation failed - JavaScript heap out of memory报错
"scripts": {
"android": "NODE_OPTIONS=--max_old_space_size=8192 react-native run-android",
"ios": "NODE_OPTIONS=--max_old_space_size=8192 react-native run-ios",
"start": "NODE_OPTIONS=--max_old_space_size=8192 react-native start",
"test": "jest"
},
然后测试使用就OK了。
第一次运行yarn android 的时候可能加载js会卡在98%的位置,等一会就好了。
