Hamid
Hamid

Reputation: 2098

Detect if react-native project is being run on Expo

I need to support expo in one of my open-source projects. I would like to load a specific module when the project is being run on Expo otherwise load another module and work with that. One of the solutions would be using resolve('module') to check if the specific module is available or not, but my question is, is there any other ways to detect if the project is based on Expo or not?

Upvotes: 2

Views: 1692

Answers (2)

Giacomo Cerquone
Giacomo Cerquone

Reputation: 2478

Right now they deprecated the accepted answer in favor of using the require keyword and wrapping it into a try/catch block. A little example:

let camera;
try {
  camera = require("expo-camera");
} catch {
  camera = require("another-camera-package");
}
module.exports = camera;

Reference: https://github.com/expo/fyi/blob/main/expo-extension-migration.md#before

Upvotes: 2

dcangulo
dcangulo

Reputation: 2107

I don't know if this is the answer, this is what worked for me.

Instead of doing this:

const expo = true;
let something;

if (expo) something = require('expo');
else {
  const { NativeModules } = require('react-native');
  something = NativeModules.MyNativeModule.something;
}

// use something here

I used a custom file extension (.expo.js).

Vanilla:

// MyComponent.js
import { NativeModules } from 'react-native';
const { something } = NativeModules.MyNativeModule;

// use something here

Expo:

// MyComponent.expo.js
import something from 'expo';

// use something here

Expo will automatically use the .expo.js file.

Upvotes: 0

Related Questions