1import NativeModulesProxy from './NativeModulesProxy'; 2 3type ExpoObject = { 4 modules: 5 | undefined 6 | { 7 [key: string]: any; 8 }; 9 uuidv4: () => string; 10}; 11 12declare global { 13 // eslint-disable-next-line no-var 14 var expo: ExpoObject | undefined; 15 16 /** 17 * @deprecated `global.ExpoModules` is deprecated, use `global.expo.modules` instead. 18 */ 19 // eslint-disable-next-line no-var 20 var ExpoModules: 21 | undefined 22 | { 23 [key: string]: any; 24 }; 25} 26 27/** 28 * Imports the native module registered with given name. In the first place it tries to load 29 * the module installed through the JSI host object and then falls back to the bridge proxy module. 30 * Notice that the modules loaded from the proxy may not support some features like synchronous functions. 31 * 32 * @param moduleName Name of the requested native module. 33 * @returns Object representing the native module. 34 * @throws Error when there is no native module with given name. 35 */ 36export function requireNativeModule<ModuleType = any>(moduleName: string): ModuleType { 37 const nativeModule = requireOptionalNativeModule<ModuleType>(moduleName); 38 39 if (!nativeModule) { 40 throw new Error(`Cannot find native module '${moduleName}'`); 41 } 42 return nativeModule; 43} 44 45/** 46 * Imports the native module registered with the given name. The same as `requireNativeModule`, 47 * but returns `null` when the module cannot be found instead of throwing an error. 48 * 49 * @param moduleName Name of the requested native module. 50 * @returns Object representing the native module or `null` when it cannot be found. 51 */ 52export function requireOptionalNativeModule<ModuleType = any>( 53 moduleName: string 54): ModuleType | null { 55 return ( 56 globalThis.expo?.modules?.[moduleName] ?? 57 globalThis.ExpoModules?.[moduleName] ?? 58 NativeModulesProxy[moduleName] ?? 59 null 60 ); 61} 62