Expo Go集成Amplify报错:Cannot read property 'configure' of undefined
解决Expo GO中Amplify.configure报错"cannot read property 'configure' of undefined"
问题场景
全新Expo GO项目,参照AWS官方示例配置Amplify后,运行时抛出错误:
Uncaught Error: cannot read property 'configure' of undefined
项目代码与配置如下:
App.js代码
import { StatusBar } from 'expo-status-bar'; import * as FileSystem from 'expo-file-system'; import { StyleSheet, Text, View } from 'react-native'; import Amplify from 'aws-amplify'; import amplifyconfig from './src/amplifyconfiguration.json'; Amplify.configure(amplifyconfig); export default function App() { return ( <View style={styles.container}> <Text>Open up App.js to start working on your app!</Text> <StatusBar style="auto" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
package.json配置
{ "name": "locapp-10", "version": "1.0.0", "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web" }, "dependencies": { "@aws-amplify/react-native": "^1.0.16", "@aws-amplify/ui-react-native": "^2.1.2", "@react-native-async-storage/async-storage": "^1.22.0", "@react-native-community/netinfo": "^11.3.0", "amazon-cognito-identity-js": "^6.3.7", "aws-amplify": "^6.0.16", "expo": "~50.0.7", "expo-status-bar": "~1.11.1", "react": "18.2.0", "react-native": "0.73.4", "react-native-get-random-values": "^1.9.0", "react-native-url-polyfill": "^2.0.0" }, "devDependencies": { "@babel/core": "^7.20.0" }, "private": true }
项目搭建步骤
$ npx create-expo-app ./scratchpad-expo-amplify $ cd scratchpad-expo-amplify $ amplify init $ npm install @aws-amplify/ui-react-native aws-amplify amazon-cognito-identity-js react-native-url-polyfill $ npm install aws-amplify @aws-amplify/react-native @react-native-community/netinfo @react-native-async-storage/async-storage react-native-get-random-values@1.9.0 $ npx expo start
问题原因
使用的aws-amplify版本为v6.x,而代码中采用了v5.x的默认导入方式。Amplify v6重构了导出结构,不再提供默认导出的Amplify对象,直接import Amplify from 'aws-amplify'会得到undefined,导致调用configure方法时报错。
解决方案
1. 修改Amplify导入方式
将App.js中的导入语句从:
import Amplify from 'aws-amplify';
改为v6的命名导入:
import { Amplify } from 'aws-amplify';
2. 清理重复依赖
项目搭建步骤中重复安装了aws-amplify和@aws-amplify/react-native,建议执行以下命令清理冗余依赖并重新安装:
$ npm uninstall aws-amplify @aws-amplify/react-native $ npm install aws-amplify @aws-amplify/react-native @react-native-community/netinfo @react-native-async-storage/async-storage react-native-get-random-values@1.9.0
3. 验证配置文件路径
确认amplifyconfiguration.json文件确实存在于./src/目录下,路径无误。
完成以上修改后,重新启动Expo项目即可解决该报错。
内容的提问来源于stack exchange,提问作者Richard Stimson
相关产品推荐
相关产品推荐

