Unable to resolve module crypto - react-native

I am attempting to implement WalletConnect V1 in my React-Native Wallet app. However, whenever I use the following import:
import WalletConnect from "#walletconnect/client";
I get the following error:
Unable to resolve module crypto from /Users/<my-name>/<company-name>/<client-name>/<app-name>/node_modules/#walletconnect/randombytes/dist/cjs/node/index.js: crypto could not be found within the project or in these directories:
node_modules
I tried following some solutions but installing crypto-js and crypto-js#3.3.0 both did not fix the issue. I also already have react-native-crypto installed in my application.
Any help figuring out what I need to do to resolve this error would be amazing!

Just add custom resolver to your metro config
// metro.config.js
module.exports = {
resolver: {
extraNodeModules: {
crypto: require('react-native-cyrpto'),
},
},
};
Unfortunately crypto depends on other nodejs packages like: net, tls, fs and etc. Recommend using https://github.com/parshap/node-libs-react-native which polyfills node packages inside react-native
Docs
tldr;
nom install node-libs-react-native
// metro.config.js
module.exports = {
resolver: {
extraNodeModules: require('node-libs-react-native'),
},
};

I managed to solve this thanks to this post (https://github.com/parshap/node-libs-react-native/issues/23)
yarn add react-native-get-random-values
const nodelibs = require("node-libs-react-native");
nodelibs.crypto = `${__dirname}/src/crypto.js`;
module.exports = {
resolver: {
extraNodeModules: nodelibs,
},
};
Then created my own crypto.js file
// src/crypto.js
'use strict'
import { Buffer } from 'buffer';
const { NativeModules } = require('react-native');
const randomBytes = (size) => {
if (NativeModules.RNGetRandomValues) {
return Buffer(NativeModules.RNGetRandomValues.getRandomBase64(size));
} else {
throw new Error('Native module not found')
}
};
exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = randomBytes;

Related

getting error after upgrading to expo sdk 44 to 46

I have upgraded my expo application which was expo sdk 44 to expo sdk 46.
After upgrading I got this error and trying to figure this for last 4 days. Any help would be helpful..
Here is the error:
ERROR Invariant Violation: ViewPropTypes has been removed from React Native. Migrate to ViewPropTypes exported from 'deprecated-react-native-prop-types'.
Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:95:4 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:141:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError
at node_modules/expo/build/errors/ExpoErrorManager.js:25:19 in errorHandler
at node_modules/expo/build/errors/ExpoErrorManager.js:30:24 in <anonymous>
at node_modules/#react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError
Steps I followed:
Upgraded Expo SDK into 45 and compiled successfully and then upgraded again into SDK 46
Tried registerRootComponent from a file named main.js refernece from expo
Also tried this answer which refers the multiple copies of react-native-safe-area-context tried this solution also
Fixed this issue:
Step 1:
Install the plugin
yarn add --dev babel-plugin-module-resolver deprecated-react-native-prop-types
Step 2:
create index.js file inside project folder resolver/react-native/ with following code
import * as StandardModule from 'react-native';
const deprecatedProps = {
ImagePropTypes: require('deprecated-react-native-prop-types/DeprecatedImagePropType'),
TextPropTypes: require('deprecated-react-native-prop-types/DeprecatedTextPropTypes'),
ViewPropTypes: require('deprecated-react-native-prop-types/DeprecatedViewPropTypes'),
ColorPropType: require('deprecated-react-native-prop-types/DeprecatedColorPropType'),
EdgeInsetsPropType: require('deprecated-react-native-prop-types/DeprecatedEdgeInsetsPropType'),
PointPropType: require('deprecated-react-native-prop-types/DeprecatedPointPropType'),
};
const imgProx = new Proxy(StandardModule.Image, {
get(obj, prop) {
if (prop === 'propTypes') return deprecatedProps.ImagePropTypes;
return Reflect.get(...arguments);
},
});
const txtProx = new Proxy(StandardModule.Text, {
get(obj, prop) {
if (prop === 'propTypes') return deprecatedProps.TextPropTypes;
return Reflect.get(...arguments);
},
});
// Had to use a proxy because ...StandardModule made think react-native that all modules were
// being used and was triggering some unnecessary validations / native dep checks.
// This prevents that from happening.
const objProx = new Proxy(StandardModule, {
get(obj, prop) {
if (prop in deprecatedProps) {
return deprecatedProps[prop];
}
if (prop === 'Image') {
return imgProx;
}
if (prop === 'Text') {
return txtProx;
}
return Reflect.get(...arguments);
},
});
module.exports = objProx;
Step 3:
configure module resolver inside babel.config.js, depends on your project requirement to blacklist/whitelist certain npm packages to prevent conflicting file.
example module-resolver config :
var path = require('path');
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
["module-resolver", {
"root": ["."],
resolvePath(sourcePath, currentFile, opts) {
if (
sourcePath === 'react-native' &&
!(
(
currentFile.includes('node_modules/react-native/') || // macos/linux paths
currentFile.includes('node_modules\\react-native\\')
) // windows path
) &&
!(
currentFile.includes('resolver/react-native/') ||
currentFile.includes('resolver\\react-native\\')
)
) {
return path.resolve(__dirname, 'resolver/react-native');
}
/**
* The `opts` argument is the options object that is passed through the Babel config.
* opts = {
* extensions: [".js"],
* resolvePath: ...,
* }
*/
return undefined;
}
}],
],
};
for reference this guide

react native Android Cannot access realm that has been closed

im using Realm inside my React native app, in IOS everything work fine, but with Android I always got this error: Cannot access realm that has been closed
here is my Realm:
RealmContext.js
import { ContactInfo, Room, RoomBackground, RoomDetail, RoomMessage, Summary } from "../database/RealmSchemas"
import { Realm, createRealmContext } from '#realm/react'
const config = {
schema: [Room.schema,
ContactInfo.schema,
RoomDetail.schema,
RoomBackground.schema,
Summary.schema,
RoomMessage.schema],
}
export default createRealmContext(config)
Other class
import RealmContext from '../../context/RealmContext'
const { useRealm, useQuery } = RealmContext
export class....{
const realm = useRealm()
const getRoomDetailFromDb = () => {
try {
const roomDetailDb = realm.objectForPrimaryKey('RoomDetail', room.RoomId)
if (roomDetailDb != null) {
roomDetail = JSON.parse(roomDetailDb.value)
}
} catch (error) {
console.log(error)
}
}
here is my version of realm:
"realm": "^10.18.0",
"#realm/react": "^0.3.0",
i did following the site: https://www.mongodb.com/docs/realm/sdk/react-native/use-realm-react/
Seems like react-native-reanimated lib is not compatible with Realm v10 on Android.
In case you use that please try realm#11.0.0-rc.0. It works fine after I upgrade realm version to v11. Even though it's not a stable version.

Error: While trying to resolve module #apollo/client React Native

after installing new version of apollo client getting this Error. I tried other versions and to downgrade but nothing. Also I tried to specify in metro.config.js to resolve "cjs" type of file (#apollo/client/main.cjs), but nothing.
Error
error: Error: While trying to resolve module `#apollo/client` from file `****\src\api\queries\home.js`, the package `****\node_modules\#apollo\client\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`****\node_modules\#apollo\client\main.cjs`. Indeed, none of these files exist:
Dependencies
"#apollo/client": "^3.3.2",
"graphql": "^15.4.0",
Anyone can help me please? Will be very thankful!
As documented at https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19, the solution should be to add
const { getDefaultConfig } = require("metro-config");
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
exports.resolver = {
...defaultResolver,
sourceExts: [
...defaultResolver.sourceExts,
"cjs",
],
};
in your metro.config.js.
In my case, I already have a module.exports generated by default, so I just had to make the file so:
const {getDefaultConfig} = require('metro-config');
const {resolver: defaultResolver} = getDefaultConfig.getDefaultValues();
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
...defaultResolver,
sourceExts: [...defaultResolver.sourceExts, 'cjs'],
},
};
Simply adding cjs file extension to metro.config.js works for me.
According to expo's Official Adding more file extensions to assetExts documentation...
const { getDefaultConfig } = require('#expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('cjs');
module.exports = defaultConfig;
I have exactly the same problem in react-native.
From the documentation, it follows that you need to add the ability to handle "cjs" files.
https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19
Solved the problem today by adding to node_modules/metro-config/src/defaults/defaults.js
export.sourceExts = ["js", "json", "ts", "tsx", "cjs"];
and from the project folder
for android:
cd android && ./gradlew clean
for ios in xcode :
clean -> run
For Expo Projects, We need to add cjs to sourceExts.
const { getDefaultConfig } = require('#expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.sourceExts.push('cjs');
module.exports = defaultConfig;
Apollo Docs for source extension https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19
Expo syntax for metro config https://docs.expo.dev/guides/customizing-metro/

Main module field cannot be resolved after installing #apollo/client

I'm running into an error after installing Apollo when trying to run my React Native Expo app. I've tried deleting node-modules and re-installing, resetting cache, restarting computer, and still no luck.
Android Bundling failed 456ms
While trying to resolve module #apollo/client from file >/mnt/c/Users/14044/Desktop/Coding/divii/client/App.tsx, the package >/mnt/c/Users/14044/Desktop/Coding/divii/client/node_modules/#apollo/client/package.json >was successfully found. However, this package itself specifies a main module field that >could not be resolved >(/mnt/c/Users/14044/Desktop/Coding/divii/client/node_modules/#apollo/client/main.cjs. Indeed, none of these files exist:
/mnt/c/Users/14044/Desktop/Coding/divii/client/node_modules/#apollo/client/main.cjs(.native|.android.jsx|.native.jsx|.jsx|.android.js|.native.js|.js|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.json|.native.json|.json)
/mnt/c/Users/14044/Desktop/Coding/divii/client/node_modules/#apollo/client/main.cjs/index(.native|.android.jsx|.native.jsx|.jsx|.android.js|.native.js|.js|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.json|.native.json|.json)
This is a conflict between #apollo/client v3.5.4 and RN metro bundler.
As a workaround until this issue is resolved, you can configure Metro by creating a metro.config.js file in the root of your React Native project with following content:
const { getDefaultConfig } = require("metro-config");
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
exports.resolver = {
...defaultResolver,
sourceExts: [
...defaultResolver.sourceExts,
"cjs",
],
};
This workaround was posted on Apollo Github Releases page
here.
This is an issue with the latest version of Apollo Client (3.5.0 and up) and the way Metro bundler works. You need to configure Metro to understand the .cjs files used in #apollo/client by creating a metro.config.js in the root folder of your project.
Here is the link to a solution on the Apollo releases page.
I tried the solution, it didn't work, the error was solved, but the build broke for other packages in the project, so I tried a similar but different approach
Here is my metro.config.js
const {getDefaultConfig} = require('metro-config');
module.exports = (async () => {
const {
resolver: {sourceExts},
} = await getDefaultConfig();
return {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
sourceExts: [...sourceExts, 'cjs'],
},
};
})();
Try downgrading to #apollo/client 3.4.16. I just did a round of package updates and the 3.5.4 broke my build as well. I'm using the downgraded package with a downgraded version of graphql lib as well -- 15.7.2.
Those are the last versions that worked for me with the current version of Expo / RN.
Hope that helps you out!
For anyone using Expo and the new Apollo Client, you should update your metro.config.js to look like this:
const { getDefaultConfig } = require('#expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.sourceExts.push('cjs');
module.exports = defaultConfig;
It's important to make sure you use the expo metro config defaults otherwise eas will complain at build time.
Had the same issue in a Vanilla/Bare React Native Project with Apollo Client 3.5.8
The project already had the default metro.config.js
I just modified it to the following code :
const {getDefaultConfig} = require('metro-config');
const {resolver: defaultResolver} = getDefaultConfig.getDefaultValues();
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
...defaultResolver,
sourceExts: [...defaultResolver.sourceExts, 'cjs'],
},
};
With this change the issue was resolved

Unable to resolve module tensorflow_inception_graph.pb as a file nor as a folder

Here I am using tensor flow with react native using react-native-tensorflow llibrary. The library has installed properly. The code snippet which I am using and facing an issue is
const tfImageRecognition = new TfImageRecognition({
model: require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt'),
imageMean: 117, // Optional, defaults to 117
imageStd: 1 // Optional, defaults to 1 })
In the model property, when I am loading the tensorflow_inception_graph.pb file then it is giving me the error
error: bundling failed: UnableToResolveError: Unable to resolve module
`../asset/tensorflow_inception_graph.pb` from
`/Users/XYZ/App/code/Demo/src/ImageRecognitionAI.js`:
could not resolve `/Users/XYZ/App/code/Demo/src/assets/tensorflow_inception_graph.pb'
as a file nor as a folder
The file path which I am passing in model is checked and found correct. Can anyone help me to get out of this? Help will be appreciated.
place the tenserflow_labels.text and tensorflow_inception_graph.pb and file in the assets folder
=> android/app/src/main/assets/tensorflow_inception_graph.pb
=> android/app/src/main/assets/tenserflow_labels.text
now you can access it like this in your js file.
const tf = new TfImageRecognition({
model: 'file://tensorflow_inception_graph.pb',
labels: 'file://tenserflow_labels.txt'
});
it worked for me.
You have to specify the webpack type extensions in either the package or a rn-cli.config.js file. If you're using create-react-native-app then you want to add it to the app.json file like this:
{
"expo": {
"sdkVersion": "27.0.0",
"packagerOpts": {
"assetExts": ["pb", "txt"]
}
}
}
I didn't find that in the documentation for some reason, but I found it in some example projects.
If you're running your scripts with react-native start then you need to setup a rn-cli.config.js file. Here is the documentation
module.exports = {
getAssetExts() {
return ['pb', 'txt']
}
}
If you are running scripts from rn-cli.config.js
change file content to :
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { assetExts }
} = await getDefaultConfig();
return {
resolver: {
assetExts: [...assetExts, "pb", "txt"]
}
};
})();