'I'm unable to load @apollo/client on a React Native Expo app

I'm trying to load @apollo/client on a React Native Expo app.

And I get this error:

While trying to resolve module @apollo/client from file /Users/andrepena/git/anglio-mobile-rn/screens/dictionary/index.tsx, the package /Users/andrepena/git/anglio-mobile-rn/node_modules/@apollo/client/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/andrepena/git/anglio-mobile-rn/node_modules/@apollo/client/main.cjs. Indeed, none of these files exist

Then I searched Stackoverflow and someone said I should add this to my metro.config.json

const { getDefaultConfig } = require("@expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;

But now, all imports from @apollo/client simply return undefined.

Example:

import { ApolloClient, InMemoryCache } from "@apollo/client";
console.log(ApolloClient); // undefined
console.log(InMemoryCache); // undefined

In fact, @apollo/client is exporting this object:

Object {
  "default": 17,
}

Any suggestion?



Solution 1:[1]

This metro.config.js worked for me: (remember to install @expo/metro-config)

const { getDefaultConfig } = require('@expo/metro-config');

const config = getDefaultConfig(__dirname, {
    // Initialize in exotic mode.
    // If you want to preserve `react-native` resolver main field, and omit cjs support, then leave this undefined
    // and skip setting the `EXPO_USE_EXOTIC` environment variable.
    mode: 'exotic',
});

module.exports = config;

The exotic thing makes Metro to be able to find the weird cjs module that @apollo/client exports

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1