3

This question has already been asked but has never received a clear answer. Plus, the questions are old and in the blockchain space, a one-year old question is obsolete. This question is for React Native and version 0.51 and web3 version 1.0-beta

Hi,

I am trying to create a React Native application that uses web3js but I am unable to actually import it. The error is pretty obvious but I don't know how to solve it.

attempted to import the Node standard library module "crypto". It failed because React Native does not include the Node standard library.

Is the error due to Expo? Should I eject? Have anyone actually solved this?

Thanks, Dario

4

There is some documentation about React native that will helps you to understand why some packages are not possible to be included into React Native applications.

if the package depends on Node standard library APIs, you will not be able to use it with Expo. The Node standard library is a set of functionality implemented largely in C++ that exposes functions to JavaScript that aren't part of the JavaScript language specification, such as the ability to read and write to your filesystem. React Native, and by extension Expo, do not include the Node standard library, just like Chrome and Firefox do not include it. JavaScript is a language that is used in many contexts, from mobile apps (in our case), to servers, and of course on websites. These contexts all include their own runtime environments that expose different APIs to JavaScript, depending on what makes sense in the context. ref

So said you can try to include the dist files instead of the package. When you include the package via Nodejs it will be compiled (if its required) and possibly will use some Node standard libraries.

You can find the web3 dist here and since its pure javascript (that will run in the browser), it should work also in React native. According to this page.

  • Maybe I am doing something wrong but this approach doesn't work. But the explanation is accurate. I think the way to fix this is to shim the "crypto" package – Dario Anongba Varela Apr 20 '18 at 12:40
  • crypto is a Node Standard library: nodejs.org/api/crypto.html so you have some modules that use this dependency and that's why you are having the described error. So just uninstall the packages and use the dist. Provided that the issue is related to web3 and not other dependencies – mirg Apr 20 '18 at 15:26
  • I already said that it does not work. Please do not answer if you haven't tried. Using the dist is not the solution. I think that the solution is to eject, install react-native-crypto and use rn-nodeify to shim it. I'll let you know when I make it work. – Dario Anongba Varela Apr 22 '18 at 15:48
  • I tried to help you, but if you already know the solution then that's better. cheers – mirg Apr 23 '18 at 2:26
2

Just something missing in @Andy Malkin answer: add global.js file

// Inject node globals into React Native global scope.

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');
  };
}

then import it in the app.js

import "./global"
1

I covered this in a blog post a little while ago for the web3 0.20.x line: https://medium.com/@generalpiston/how-to-react-native-w-web3-0x-js-0xconnect-39b3d6a4dca.

The steps are roughly the same for the web3 1.x line as well.

Several node.js libraries are missing in react-native and isomorphic-fetch doesn’t work well with react-native. To get it working, follow these steps:

  1. npm i -S abec/node-libs-react-native.
  2. Add the following to rn-cli.config.js:

const extraNodeModules = require("node-libs-react-native");

module.exports = { extraNodeModules };

  1. Add the following to the top of your root index.js file:

import "node-libs-react-native/globals";

  1. Add the following config to your package.json under the scripts section:

"prepare": "npm run patch",

"patch": "find ./node_modules -name fetch-npm-browserify.js -print -exec sed -i.bk 's/self/global/g' {} \;"

0

i got web3 up and running with RN59 and React 16.8

react-native init APPNAME

npm i --save react-native-crypto

npm i --save react-native-randombytes

react-native link react-native-randombytes

npm i --save-dev rn-nodeify@latest

./node_modules/.bin/rn-nodeify --install

npm i --save node-libs-browser

modify APPNAME/metro.config.js to read:

const extraNodeModules = require('node-libs-browser');

module.exports = {
  resolver: {
    extraNodeModules,
  },
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
  },
};

modify shim.js to read:

if (typeof __dirname === 'undefined') global.__dirname = '/'
if (typeof __filename === 'undefined') global.__filename = ''
if (typeof process === 'undefined') {
  global.process = require('process')
} else {
  const bProcess = require('process')
  for (var p in bProcess) {
    if (!(p in process)) {
      process[p] = bProcess[p]
    }
  }
}

process.browser = false
if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer

if (typeof location === 'undefined') global.location = { port: 80, protocol: 'https:' }
const isDev = typeof __DEV__ === 'boolean' && __DEV__
process.env['NODE_ENV'] = isDev ? 'development' : 'production'
if (typeof localStorage !== 'undefined') {
  localStorage.debug = isDev ? '*' : ''
}

// If using the crypto shim, uncomment the following line to ensure
// crypto is loaded first, so it can populate global.crypto
require('crypto')

import './shim' in App.js

npm i --save web3

react-native run-ios

-1

It seems like some others were successful:

How to set up web3.js with CRNA

This is a simple guide to get you started with using the Ethereum Javascript API (web3.js) with the Create React Native App project. This is not an in-depth guide.

TL;DR If you are lazy and just want to get started, I have this project ready for

you. It should work out-of-the-box.

Installation guide

  1. Make sure you have Node version 6 or later installed, if not, get it on the Node website

    node --version

  2. Install Create React Native App

    npm install -g create-react-native-app

  3. Use create-react-native-app to create the project boilerplate

    create-react-native-app my-app

  4. Install node-libs-browser (redacted link because of reputation)

    npm install --save node-libs-browser

  5. Create a file called rn-cli.config.js on the root of the project and add the following code into it:

    ```javascript const extraNodeModules = require('node-libs-browser');

    module.exports = { extraNodeModules, }; ```

  6. Create a file called global.js on the root of the project and add the following code into it:

    ```javascript // Inject node globals into React Native global scope. 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'); }; }

    ```

  7. Import the global.js file into your App.js file

    javascript import './global';

  8. Install babel-preset-es2015 npm install --save-dev babel-cli babel-preset-es2015

  9. Now we can install the web3.js api

    npm install --save web3

  10. Require the API in your App.js file

    javascript const Web3 = require('web3');

  11. Add the following code inside your React component in App.js to get started with consuming the API. The code will print information of the latest block on the console.

    ```javascript componentWillMount() { const web3 = new Web3( new Web3.providers.HttpProvider('link redacted because of reputation limit') );

    web3.eth.getBlock('latest').then(console.log) } ```

  12. Test it

    npm start

    or npm run ios

    or

    npm run android

For more examples on the API usage, visit the web3.js API.

For a project with all this setup ready, check out [link redacted because of link limit on reputation).

Sources:

https://gist.github.com/dougbacelar/29e60920d8fa1982535247563eb63766 https://github.com/ethereum/web3.js/issues/1022

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.