Skip to main content

本地库设置

本地库是包含视图或模块的库,这些视图或模块是应用本地的,不会发布到注册表。这与视图和模块的传统设置不同,因为本地库与你应用的原生代码分离。

¥A local library is a library containing views or modules that's local to your app and not published to a registry. This is different from the traditional setup for view and modules in the sense that a local library is decoupled from your app's native code.

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

¥The local library is created outside of the android/ and ios/ folders and makes use of autolinking to integrate with your app. The structure with a local library may look like this:

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 版本、复制到其他项目等会更加容易。

¥Since a local library's code exists outside of android/ and ios/ folders, it makes it easier to upgrade React Native versions in the future, copy to other projects etc.

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

¥To create local library we will use create-react-native-library. This tool contains all the necessary templates.

入门

¥Getting Started

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

¥Inside your React Native application's root folder, run the following command:

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

其中 awesome-module 是你想要的新模块的名称。按照提示操作后,项目根目录中会有一个名为 modules 的新文件夹,其中包含新模块。

¥Where awesome-module is the name you would like for the new module. After going through the prompts, you will have a new folder called modules in your project's root directory which contains the new module.

Linking

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

¥By default, the generated library is automatically linked to the project using link: protocol when using Yarn and file: when using npm:

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

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

¥This creates a symlink to the library under node_modules which makes autolinking work.

安装依赖

¥Installing dependencies

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

¥To link the module you need to install dependencies:

npm install

在你的应用内使用模块

¥Using module inside your app

要在应用中使用该模块,你可以通过其名称导入它:

¥To use the module inside your app, you can import it by its name:

import {multiply} from 'awesome-module';