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
Related
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;
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/
I recently began development on a React Native/Expo project and had been making use of custom fonts and expo icons just fine up until I changed my metro.config.js settings to allow for the import of SVG files as React Native components.
SVGs are working fine now but the custom fonts are no longer being recognized, I'm receiving the error:
"Unrecognized font family "Maquette400" "
My current metro config settings are as follows:
const { getDefaultConfig } = require('#expo/metro-config');
const {
resolver: { sourceExts, assetExts },
} = getDefaultConfig(__dirname);
module.exports = {
transformer: {
assetPlugins: ['expo-asset/tools/hashAssetFiles'],
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
babelTransformerPath: require.resolve('react-native-svg-transformer'),
},
resolver: {
assetExts: assetExts.filter((ext) => ext !== 'svg'),
sourceExts: [...sourceExts, 'svg'],
},
};
These are my settings prior to setting up SVG transformer
module.exports = {
transformer: {
assetPlugins: ['expo-asset/tools/hashAssetFiles'],
},
};
From what research I've done, this seems to be a known issue when using both SVG transformer and Expo SDK 40 as I've encountered various developers also running into the same issue and resolving it in different ways, although none of the methods they've tried have resolved my problem.
If anyone has any experience with such a conflict or setting up the metro.config.js for a React Native/Expo project, it would be greatly appreciated!
Here is the link to react-native-svg-transformer and their set up instructions
SVG transformer conflicting with SASS/SCSS
SVG transformer breaking fonts/icons with SDK 40
Git issue for SVG transformer conflict with SDK 40
If you still need a solution, use this :https://github.com/gregberge/svgr
No custom metro config needed
React native documentation state that
"You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save-dev, and then edit the .babelrc file under your project directory like this"
{
"env": {
"production": {
"plugins": ["transform-remove-console"]
}
}
}
I didn't find .babelrc file. Hence I made the following changes in babel.config.js file.
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
env: {
production: {
plugins: ["transform-remove-console"]
}
}
};
But it's not working for me. The logs are displayed when I've tested them in Android Studio. What went wrong here?
The documented approach didn't work for my existing project either, but it worked in a new test project. I tried numerous dependency upgrades, adding/removing deps, plugins, etc. trying to figure out the source of the problem, but no luck. So finally I went with this workaround:
module.exports = {
plugins: ['#babel/plugin-proposal-numeric-separator', 'lodash'].concat(
process.env.NODE_ENV === 'production' ? ['transform-remove-console'] : []
),
presets: [
'module:metro-react-native-babel-preset',
['#babel/env', { targets: { node: 6 } }]
]
};
This should work (recommended method)
const presets = ['module:metro-react-native-babel-preset'];
const plugins = ['module:react-native-dotenv'];
if (process.env.ENV === 'prod') {
plugins.push('transform-remove-console');
}
module.exports = {presets, plugins};
Or if you don't want to use any package for this you can do this.
Place this in index.js
if(!__DEV__){
console.log = () => {}
}
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"]
}
};
})();