You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Expo React Native中为iOS平台排除react-native-usb-serialport-for-android包

问题描述

我有一个React Native Expo应用,使用了react-native-usb-serialport-for-android包,该包在Android设备上运行正常,但在iOS平台运行时出现如下错误:

Error: The package 'react-native-usb-serialport-for-android' doesn't seem to be linked. Make sure: 

- You have run 'pod install'
- You rebuilt the app after installing the package
- You are not using Expo managed workflow

我尝试了以下解决方案,但未达到预期效果:

  • 在package.json中配置:
"expo": {
    "autolinking": {
      "ios": {
        "exclude": [
          "react-native-usb-serialport-for-android"
        ]
      }
    }
  }
  • 在react-native.config.js中配置:
module.exports = {
   dependencies: {
      'react-native-usb-serialport-for-android': { platforms: { ios: null } } 
  } 
}

需要可行方案,让iOS平台排除该库,同时不影响Android平台使用!

可行解决方案

方案1:平台条件导入(代码层面隔离)

在所有使用该库的代码中,仅在Android环境下导入和调用相关功能,iOS环境下完全跳过:

import { Platform } from 'react-native';

// 仅Android平台导入库
let UsbSerialPort = null;
if (Platform.OS === 'android') {
  UsbSerialPort = require('react-native-usb-serialport-for-android').default;
}

// 使用时添加平台判断
const handleUsbAction = () => {
  if (Platform.OS === 'android' && UsbSerialPort) {
    // 执行USB串口相关操作
    UsbSerialPort.openDevice(...);
  }
};

方案2:Expo预构建项目的Podfile补丁

如果你的项目是Expo预构建(已执行expo prebuild),可以通过修改Podfile强制iOS排除该库:

  1. 删除之前在package.json和react-native.config.js中的无效配置
  2. 在项目根目录创建ios/Podfile.patch文件,内容如下:
diff --git a/ios/Podfile b/ios/Podfile
index abc123..def456 100644
--- a/ios/Podfile
+++ b/ios/Podfile
@@ -10,6 +10,9 @@ target 'YourAppName' do
   use_expo_modules!
   config = use_native_modules!

+  # 排除react-native-usb-serialport-for-android在iOS构建
+  pod 'react-native-usb-serialport-for-android', :path => '../node_modules/react-native-usb-serialport-for-android', :platforms => []
+
   post_install do |installer|
     react_native_post_install(installer)
     __apply_Xcode_12_5_M1_post_install_workaround(installer)
  1. 进入ios目录应用补丁并重新安装Pods:
cd ios
patch Podfile < Podfile.patch
pod install --repo-update
cd ..

方案3:使用Expo Build Properties插件(推荐)

通过Expo官方插件在构建配置中直接排除iOS平台的该库:

  1. 安装插件:
npx expo install expo-build-properties
  1. 在app.json或app.config.js中添加插件配置:
{
  "expo": {
    "plugins": [
      [
        "expo-build-properties",
        {
          "ios": {
            "extraPods": [
              {
                "name": "react-native-usb-serialport-for-android",
                "platforms": []
              }
            ]
          }
        }
      ]
    ]
  }
}
  1. 清理并重新预构建iOS项目:
npx expo prebuild --clean --platform ios
npx expo run:ios

注意:无论使用哪种方案,都必须确保代码中没有在iOS环境下调用该库的逻辑,否则会出现运行时错误。

内容的提问来源于stack exchange,提问作者Lakpriya Senevirathna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:15:11