本地函式庫設定
本地函式庫是一種包含視圖或模組的函式庫,它位於您的應用程式本地,且未發佈到註冊中心。這與視圖和模組的傳統設定不同,因為本地函式庫與您應用程式的原生程式碼解耦。
本地函式庫在 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 應用程式的根資料夾中,執行以下命令
終端
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
終端
npm install
終端
yarn install
在您的應用程式中使用模組
要在您的應用程式中使用模組,您可以使用其名稱導入它
js
import {multiply} from 'awesome-module';