本地库设置
本地库是一个包含视图或模块的库,它位于你的应用程序本地,并且没有发布到注册中心。这与传统的视图和模块设置不同,因为本地库与你应用程序的本地代码解耦。
本地库是在 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:`。
- npm
- Yarn
json
"dependencies": {
"awesome-module": "file:./modules/awesome-module"
}
json
"dependencies": {
"awesome-module": "link:./modules/awesome-module"
}
这会在 node_modules
下创建到库的符号链接,从而使自动链接生效。
安装依赖
要链接模块,你需要安装依赖。
- npm
- Yarn
shell
npm install
shell
yarn install
在你的应用中使用模块
要在你的应用中使用模块,你可以通过其名称导入它。
js
import {multiply} from 'awesome-module';