In some cases, you may need to integrate a custom React Native package that is not hosted on NPM. If you directly copy the package into the node_modules
folder, it will get deleted when you run npm install
or yarn install
, as the package manager updates dependencies from the registry.
To persist the package, you need to set it up as a local dependency. In this article I will explains how to properly integrate a local package into your React Native project.
Setting Up a Local Library
A local library is a custom module that is not published on NPM but is integrated into your app using autolinking. Instead of modifying the android/ and ios/ folders directly, the local package remains decoupled from the app's native code.
Folder Structure
Organize your project by placing the local package inside the src/packages
folder:
my-react-native-app/
│── src/
│ ├── packages/
│ │ ├── react-native-custom-package/
│ │ │ ├── index.js
│ │ │ ├── package.json
│── package.json
│── node_modules/
Adding the Local Package to package.json
Using Yarn
For Yarn, use the link:
protocol:
"dependencies": {
"react-native-custom-package": "link:./src/packages/react-native-custom-package"
}
Using NPM
For NPM, use the file:
protocol:
"dependencies": {
"react-native-custom-package": "file:./src/packages/react-native-custom-package"
}
Installing Dependencies
Once the package reference is added to package.json, install the dependencies:
yarn install # For Yarn
or
npm install # For NPM
Using the Local Package in Your App
You can now import and use the local package in your React Native project as if it were a regular dependency:
import { multiply } from 'react-native-custom-package';
const result = multiply(2, 3);
console.log(result); // Output: 6
Summary
- Place the local package inside
src/packages/
. - Reference it in
package.json
usingfile:
for NPM orlink:
for Yarn. - Run
yarn install
ornpm install
to link the package. - Import and use it like a normal module in your project.
By following these steps, you ensure that your local package persists and remains functional even after running dependency installation commands. This method is useful for custom modules, testing, or developing packages before publishing them on NPM.
Top comments (0)