Skip to content

ipfs-shipyard/js-libp2p-react-native

Repository files navigation

Running js-libp2p under React Native

There is some setup that needs to be done to modernise the react-native runtime.

  1. Turn on exports map support
// metro.config.js
module.exports = {
  resolver: {
    unstable_enablePackageExports: true,
  }
}
  1. 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
  1. Enable modern JS features
$ npm i -D @babel/plugin-transform-private-methods
// babel.config.js
module.exports = {
  //... other config
  plugins: [
    ['@babel/plugin-transform-private-methods', { loose: true }]
  ]
}

Running

Prerequisites

Make sure you have completed the React Native - Environment Setup instructions till "Creating a new application" step, before proceeding.

Run in the simulator

Start Expo:

$ npm i
$ npm start

Follow the instructions - press i to start iOS or a for Android.

Run on a device

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

Notes

  • By default this demo uses pure-js crypto - it's not efficient enough to run on an actual device, crypto-browserify should be replaced with react-native-quick-crypto in babel.config.js for native builds
  • @libp2p/webrtc can also only run on a device since it needs native code

Debugging

Put this at the top of your app file:

import debug from 'debug'

debug.enable('libp2p:*')