React Native使用本地未发布NPM包报错:无法读取prototype属性
解决React Native引入本地NPM包时的"Cannot read property 'prototype' of undefined"错误
核心问题分析
你遇到的错误根源有三个:
- 本地包依赖路径配置错误:将
mylibrary放在node_modules内并使用file:node_modules/mylibrary作为依赖路径,违背了本地包依赖的逻辑(file:应该指向源码目录而非node_modules,后者是npm自动管理依赖的目录)。 - TypeScript代码未编译:
mylibrary是TypeScript编写的,但未编译为JavaScript,React Native的Metro打包器无法直接解析node_modules中的TS文件。 - 内部模块导入路径错误:
Notification.ts中使用绝对路径import {INotification} from 'INotification',导致模块无法被正确解析。
分步修复方案
1. 调整本地包存放位置与依赖配置
- 将
mylibrary从React Native项目的node_modules目录中移出,建议放在项目同级目录(比如../mylibrary),避免和npm自动管理的依赖混淆。 - 修改React Native项目的
package.json依赖配置:
"dependencies": { "react": "18.2.0", "react-native": "0.71.19", "mylibrary": "file:../mylibrary" }
2. 修复mylibrary内部的导入路径
修改mylibrary/src/Notification.ts中的导入语句,使用相对路径:
// 替换原绝对路径导入 import {INotification} from './INotification'; export class Notification implements INotification { private readonly _name: string; private _body?: any; public constructor(name: string, body?: any) { this._name = name; this._body = body; } public get name(): string { return this._name; } public get body(): any { return this._body;} }
3. 配置mylibrary的TypeScript编译
因为React Native无法直接处理未编译的TS包,需要先将mylibrary编译为JS:
- 进入
mylibrary目录,初始化npm项目:
npm init -y
- 安装TypeScript开发依赖:
npm install typescript --save-dev
- 在
mylibrary目录创建tsconfig.json,配置编译规则:
{ "compilerOptions": { "target": "ES6", "module": "CommonJS", "declaration": true, "outDir": "./dist", "strict": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
- 修改
mylibrary/package.json,指定入口文件和类型声明路径,并添加编译脚本:
{ "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "build": "tsc" } }
- 执行编译命令,生成编译后的JS文件:
npm run build
4. 重新安装依赖并清除缓存
- 回到React Native项目目录,重新安装依赖:
npm install
- 清除Metro缓存,避免旧缓存导致的问题:
npx react-native start --reset-cache
- 重新运行项目:
# Android npx react-native run-android # iOS npx react-native run-ios
验证修复
完成以上步骤后,App.js中的Notification实例应该能正常初始化,页面会正确显示a文本。
内容的提问来源于stack exchange,提问作者AppDeveloper
相关产品推荐
相关产品推荐

