Expo开发React Native应用遇依赖解析错误:Could not resolve com.github.barteksc:android-pdf-viewer:2.8.2
问题背景
使用Expo开发React Native应用,安装react-native-view-pdf依赖后,上传开发构建包时触发以下错误:
Could not resolve com.github.barteksc:android-pdf-viewer:2.8.2.
Required by:
project :app > project :react-native-view-pdfCould not resolve com.github.barteksc:android-pdf-viewer:2.8.2.
Could not get resource 'https://www.jitpack.io/com/github/barteksc/android-pdf-viewer/2.8.2/android-pdf-viewer-2.8.2.pom'.
Could not GET 'https://www.jitpack.io/com/github/barteksc/android-pdf-viewer/2.8.2/android-pdf-viewer-2.8.2.pom'. Received status code 401 from server: Unauthorized
Expo适配的解决方案
方案1:替换为Expo官方支持的PDF库
react-native-view-pdf依赖的第三方Android库出现jitpack权限限制,建议直接使用Expo生态内的工具实现PDF功能:
- 安装依赖:
npx expo install expo-document-picker expo-web-browser - 实现逻辑:通过
expo-document-picker选择本地或在线PDF文件,用expo-web-browser直接打开预览,完全规避第三方原生依赖的构建问题。
方案2:用Config Plugin修改Android构建配置
若坚持使用react-native-view-pdf,可通过Expo Config Plugin自定义Android的build.gradle配置:
- 创建自定义插件文件(如
withFixPdfViewer.js):const { withAppBuildGradle } = require('@expo/config-plugins'); module.exports = function withFixPdfViewer(config) { return withAppBuildGradle(config, async (config) => { if (config.modResults.language === 'groovy') { // 替换依赖版本为jitpack可正常访问的3.2.0-beta.1 const newBuildGradle = config.modResults.contents.replace( 'com.github.barteksc:android-pdf-viewer:2.8.2', 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1' ); config.modResults.contents = newBuildGradle; } return config; }); }; - 在
app.json/app.config.js中引入插件:{ "expo": { "plugins": ["./withFixPdfViewer.js"] } } - 清理缓存并重新预构建:
npx expo prebuild --clean
方案3:配置EAS Build构建环境
如果使用Expo的EAS Build服务,可在eas.json中添加gradle参数:
{ "build": { "development": { "android": { "gradleExtraParams": [ "-Pmaven.repo.urls=https://repo1.maven.org/maven2/,https://www.jitpack.io" ] } } } }
若仍有401错误,可在自定义Config Plugin中添加jitpack个人令牌(需在jitpack官网生成):
maven { url "https://www.jitpack.io" credentials { username = "你的jitpack用户名" password = "你的jitpack个人令牌" } }
注意事项
- 优先选择Expo官方支持的库,减少原生依赖带来的兼容性问题;
- 修改gradle配置后必须清理缓存并重新预构建;
- jitpack的401错误可能是临时权限限制,也可间隔一段时间后重试构建。
内容的提问来源于stack exchange,提问作者Pepopig

