Resolve Node.js crypto module in React Native

78 views Asked by At

I have React Native project, where I installed a npm package, which used itself crypto module of node (require('crypto')) and it causing issues with React Native. is there any modern / clean way to somehow resolve this part, and use React Native compatible library, where node crypto is "required"?

1

There are 1 answers

2
Aqeel Ahmad On

You can use rn-nodeify package which allow you to use node core modules in your React Native app.

npm install rn-nodeify

install specific shims and hack

rn-nodeify --install "fs,dgram,process,path,console" --hack

It is recommended to add this command to the "postinstall" script in your project's package.json

"scripts": {
  "start": "node node_modules/react-native/local-cli/cli.js start",
  "postinstall": "rn-nodeify --install fs,dgram,process,path,console --hack"
}

rn-nodeify will create a shim.js file in your project root directory. The first line in index.ios.js / index.android.js should be to import it (NOT require it!)

import './shim'

Example

// index.ios.js or index.android.js
// make sure you use `import` and not `require`!
import './shim.js'
// ...the rest of your code
import crypto from 'crypto'
// use crypto
console.log(crypto.randomBytes(32).toString('hex'))

for more details Visit nodeify package

Hopefully it will resolve your problem.