首页 > 解决方案 > 创建反应原生模块并在应用程序中使用它

问题描述

我想为 iOS 和 Android 创建 react-native 模块并在应用程序中使用它。

我想像本地模块一样使用它,而不是上传到 npm。

当我按照官方文档中描述的步骤进行操作时,我总是在将模块导入 App.js 文件时遇到这些错误:

从 'react-test-module' 导入 MyModule;

找不到模块“react-test-module”的声明文件。'/Users/dbellerose/Path/to/My/Module/react-test-module/index.js' 隐含了一个 'any' 类型。尝试npm install @types/react-test-modulet它是否存在或添加一个包含 `declare module 'react-test-module' 的新声明 (.d.ts) 文件;

当我运行 iOS 应用程序时:

无法react-test-module从以下位置解析模块/Users/Path/To/My/App/App.jsreact-test-moduleHaste 模块映射中不存在模块。

该消息给了我一些解决问题的提示,但它不起作用。

要解决请尝试以下方法: 1. 清除守望者手表:watchman watch-del-all。2. 删除node_modules文件夹:rm -rf node_modules && npm install. 3. 重置 Metro Bundler 缓存:rm -rf /tmp/metro-bundler-cache-*npm start -- --reset-cache. 4.删除急速缓存:rm -rf /tmp/haste-map-react-native-packager-*

那么你知道创建一个模块并在应用程序中使用它而不将包上传到 npm 的好过程是什么?

此致,

大卫

标签: iosreactjsreact-nativemodule

解决方案


以下是我可以作为清单与您分享的一些步骤:

  1. yarn global add create-react-native-module
  2. create-react-native-module MyLibrary
  3. cd 到 MyLibrary 文件夹,运行yarn install
  4. 处理你的模块

要链接到您的项目,您需要将以下内容添加到您的 package.json (路径应该是您的模块所在的任何位置)

"react-native-test-module": "file:../", 
"react-native-my-library": "file:../../react-native-my-library/"

** 请记住,如果您在模块中附加了新方法。您将需要:

  1. 从项目中删除 node_modules 和 Pod
  2. 重新执行yarn/npm install&pod install

希望能帮助到你。


推荐阅读