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

本地npm包依赖与主项目冲突:React Native版本不匹配求助

解决React Native版本不匹配问题(引入自定义npm包时)

我正在开发一个名为rn-dialog的React Native对话框组件,使用TypeScript编写,相关配置及源码如下:

Package.json

{
  "name": "rn-dialog",
  "version": "1.0.0",
  "description": "This is a simple dialog box package for react native app",
  "main": "lib/index.js",
  "types": "lib/index.d.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc"
  },
  "keywords": [
    "react-native",
    "react-native-dialog",
    "rn-dialog",
    "rn-dialog-box",
    "react",
    "react-native-dialog-box",
    "popup"
  ],
  "author": "Irfanwani <irfanwani347@gmail.com>",
  "license": "ISC",
  "files": [
    "lib"
  ],
  "peerDependencies": {
    "react": ">=18.0.0",
    "react-native": ">=0.69.6"
  },
  "devDependencies": {
    "@types/react": "^18.0.21",
    "@types/react-native": "^0.70.4",
    "typescript": "^4.8.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "jsx": "react-native",
    "lib": ["dom", "ESNext"],
    "declaration": true,
    "sourceMap": true,
    "outDir": "./lib",
    "removeComments": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "esModuleInterop": true,
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts"]
}

src/index.tsx

import React from "react";
import { Text, View } from "react-native";

const Dialog = () => {
  return (
    <View>
      <Text>This is from Dialog</Text>
      <Text>Hope it works, inshaallah!!!</Text>
    </View>
  );
};

export default Dialog;

遇到的问题

安装依赖后,本地包自动安装了最新版react和react-native,将其引入我的Expo项目时出现错误:

React Native version mismatch.
JavaScript version: 0.70.2 Native version: 0.69.0

执行npm install --production未解决问题,寻求解决方案。


解决方案

1. 移除包本地的react和react-native依赖

peerDependencies的作用是声明包依赖宿主项目提供的库,包本身不需要安装这些依赖。执行命令:

npm uninstall react react-native

2. 调整peerDependencies版本范围匹配项目

你的Expo项目使用React Native 0.69.0,当前peerDependencies要求>=0.69.6无法满足,修改package.json:

"peerDependencies": {
  "react": ">=18.0.0",
  "react-native": ">=0.69.0"
}

3. 重新构建并清理项目缓存

  • 重新构建自定义包:
    npm run build
    
  • 在Expo项目目录清理依赖和缓存:
    rm -rf node_modules
    rm package-lock.json
    npm install
    npx expo start --clear
    

4. 本地链接测试时关联宿主项目的依赖

如果用npm link本地测试,让包使用宿主项目的react和react-native版本:

# 在自定义包目录执行
npm link ../你的Expo项目路径/node_modules/react
npm link ../你的Expo项目路径/node_modules/react-native

内容的提问来源于stack exchange,提问作者Irfan wani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:05:32