本地库设置
本地库是一个包含视图或模块的库,它对你的应用程序是本地的,并且未发布到注册表。这与视图和模块的传统设置不同,因为本地库与你的应用程序的原生代码是解耦的。
本地库在 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';