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