There is some setup that needs to be done to modernise the react-native runtime.
- Turn on exports map support
// metro.config.js
module.exports = {
resolver: {
unstable_enablePackageExports: true,
}
}
- Shimming globals
Some standard JS APIs aren't available in React Native, these need to be polyfilled, hopefully not forever.
// globals.js - this should be imported at the top of your App.js file
import '@azure/core-asynciterator-polyfill'
import 'react-native-url-polyfill/auto'
import 'react-native-get-random-values'
import 'weakmap-polyfill'
import { TextEncoder, TextDecoder } from 'text-encoding'
import { EventTarget, Event } from 'event-target-shim'
import { Buffer } from '@craftzdog/react-native-buffer'
import { Crypto } from '@peculiar/webcrypto'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
global.EventTarget = EventTarget
global.Event = Event
global.AbortSignal.timeout = (ms) => {
const controller = new AbortController()
setTimeout(() => {
controller.abort(new Error('Aborted'))
}, ms)
}
global.Buffer = Buffer
global.crypto.subtle = new Crypto().subtle
- Enable modern JS features
- libp2p uses ES2022 private properties in some places, so enable transpiling them for use with React Native. At the time of writing loose mode is also required.
$ npm i -D @babel/plugin-transform-private-methods
// babel.config.js
module.exports = {
//... other config
plugins: [
['@babel/plugin-transform-private-methods', { loose: true }]
]
}
Make sure you have completed the React Native - Environment Setup instructions till "Creating a new application" step, before proceeding.
Start Expo:
$ npm i
$ npm start
Follow the instructions - press i
to start iOS or a
for Android.
See the expo docs
$ npx expo run:android --device
For iOS you will need to provision a device certificate as normal.
$ npx expo run:ios --device
- By default this demo uses pure-js crypto - it's not efficient enough to run on an actual device,
crypto-browserify
should be replaced withreact-native-quick-crypto
inbabel.config.js
for native builds @libp2p/webrtc
can also only run on a device since it needs native code
Put this at the top of your app file:
import debug from 'debug'
debug.enable('libp2p:*')