js vm報錯_polkadot-js在React Native中的使用
阿新 • • 發佈:2020-12-27
技術標籤:js vm報錯
由於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/pol kadotjsWithReactNative
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%的位置,等一會就好了。