DEV Community

Cover image for How to Add a Local Package in a React Native Project
Amit Kumar
Amit Kumar

Posted on

How to Add a Local Package in a React Native Project

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/
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

Using NPM

For NPM, use the file: protocol:

"dependencies": {
  "react-native-custom-package": "file:./src/packages/react-native-custom-package"
}
Enter fullscreen mode Exit fullscreen mode

Installing Dependencies

Once the package reference is added to package.json, install the dependencies:

yarn install  # For Yarn
Enter fullscreen mode Exit fullscreen mode

or

npm install  # For NPM
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Summary

  • Place the local package inside src/packages/.
  • Reference it in package.json using file: for NPM or link: for Yarn.
  • Run yarn install or npm 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)