Expo+React Native+TS项目集成华为AGC AppLinking遇类型及模块问题
解决Expo+React Native+TypeScript集成华为AGC AppLinking的问题
问题1:TypeScript声明文件缺失
你已通过在env.d.ts添加declare module "@react-native-agconnect/applinking";解决导入错误,这里可以优化类型提示体验:
- 在项目根目录创建单独的声明文件
agconnect-applinking.d.ts,内容如下:
declare module '@react-native-agconnect/applinking' { export interface AppLinkingAndroidLinkInfo { packageName: string; androidDeepLink: string; openType: number; } export const AppLinkingAndroidLinkInfoAndroidOpenTypeConstants: { APP_GALLERY: number; APP: number; }; // 可根据实际使用需求补充其他类型/常量定义 }
- 确保
tsconfig.json的include数组包含该文件:
{ "include": [ "src/**/*", "agconnect-applinking.d.ts" ] }
问题2:TypeError: Cannot set property 'ShortAppLinkingLengthConstants' of null
这个错误源于模块未正确初始化或Expo环境配置不全,按以下步骤排查修复:
完成AGC基础配置
- 从华为AGC控制台下载对应平台配置文件:
- Android:将
agconnect-services.json放到android/app目录下 - iOS:将
agconnect-services.plist放到ios/[你的项目名称]目录下
- Android:将
- 配置AndroidManifest.xml(裸项目需操作):添加AppLinking跳转过滤器
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="huawei.com" /> </intent-filter>- 配置iOS Info.plist:添加关联域名与网络权限
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>https</string> </array> </dict> </array>- 从华为AGC控制台下载对应平台配置文件:
适配Expo环境
- 若使用托管Expo项目,@react-native-agconnect/applinking这类原生模块无法直接兼容,需执行
expo prebuild转为裸项目后再做原生配置 - 确认当前Expo SDK版本与@react-native-agconnect/applinking 1.3.0兼容,不兼容则尝试升级/降级包版本(如1.2.0)
- 若使用托管Expo项目,@react-native-agconnect/applinking这类原生模块无法直接兼容,需执行
调整模块调用时机
- 避免在组件初始化阶段直接访问模块常量,改用
useEffect延迟调用,确保模块完成初始化:
import { useEffect, useState } from 'react'; import AgcAppLinking from '@react-native-agconnect/applinking'; export default function App() { const [androidLinkInfo, setAndroidLinkInfo] = useState(null); useEffect(() => { const initLinkInfo = () => { setAndroidLinkInfo({ packageName: "com.huawei.agc.rn.applinking.example", androidDeepLink: "https://huawei.com/", openType: AgcAppLinking.AppLinkingAndroidLinkInfoAndroidOpenTypeConstants.APP_GALLERY }); }; initLinkInfo(); }, []); // 后续使用androidLinkInfo return <View>{/* ... */}</View>; }- 避免在组件初始化阶段直接访问模块常量,改用
清理缓存并重装依赖
- 执行以下命令重置依赖与缓存:
rm -rf node_modules package-lock.json yarn.lock npm install npx expo start --clear
内容的提问来源于stack exchange,提问作者Dmitry
相关产品推荐
相关产品推荐

