跳到主要内容

本地库设置

本地库是一个包含视图或模块的库,它位于你的应用程序本地,而不是发布到注册表。这与视图和模块的传统设置不同,因为本地库与你的应用程序的原生代码解耦。

本地库创建在 android/ios/ 文件夹之外,并使用自动链接与你的应用程序集成。使用本地库的结构可能如下所示

纯文本
MyApp
├── node_modules
├── modules <-- folder for your local libraries
│ └── awesome-module <-- your local library
├── android
├── ios
├── src
├── index.js
└── package.json

由于本地库的代码存在于 android/ios/ 文件夹之外,因此更容易在将来升级 React Native 版本,复制到其他项目等。

要创建本地库,我们将使用 create-react-native-library。此工具包含所有必要的模板。

入门指南

在你的 React Native 应用程序的根文件夹中,运行以下命令

shell
npx create-react-native-library@latest awesome-module

其中 awesome-module 是你希望新模块使用的名称。在完成提示后,你将在项目的根目录中获得一个名为 modules 的新文件夹,其中包含新模块。

链接

默认情况下,当使用 Yarn 时,生成的库会自动使用 link: 协议链接到项目,当使用 npm 时,使用 file: 协议

json
"dependencies": {
"awesome-module": "file:./modules/awesome-module"
}

这会在 node_modules 下创建一个指向库的符号链接,使自动链接工作。

安装依赖

要链接模块,你需要安装依赖

shell
npm install

在你的应用程序内部使用模块

要在你的应用程序内部使用该模块,你可以通过其名称导入它

js
import {multiply} from 'awesome-module';