Lang
Blog

Monorepo for React Native Apps with Nx

ByMuskan Jain
May 19th . 5 min read
Monorepo for React Native Apps with Nx

Hey Developers!

I am a React Native Developer and received one project with two different applications, having similar business logics and UI designs. And then I realized, there will be some duplicate or redundant code in both applications, and as a developer, we should follow DRY (Don’t Repeat Yourself) principle.

That’s why, I started looking for an architecture to avoid duplicate code across the projects. And then I came across one of the most popular options to do so — MONOREPO.

In this article, You will see how you can use multiple applications with React Native in one Monorepo-

What is Monorepo ?

Firstly, let’s understand the term Monorepo -

Simply said, it is a repository that contains code for many projects and packages.

Monorepo allows you to have multiple projects share common dependencies instead of installing the dependencies for each of them, while simplifying code sharing between projects, allowing you to import code from one package to another and Redux logic.

Great! Now that we got the concept straight, let’s start implementation using Nx.

Steps to Create A Mono-repo Project

Nx is a smart, fast and extensible build system with first class monorepo support and powerful integrations.

Now, let’s make the project structure —

👉 Create a Nx workspace-

npx create-nx-workspace <your_app_name> --preset=react-native
nx generate application <your_app_name>

This should generate <your_app> folder under apps.

monorepo_1.jpg

Now you can install the starter project of Nx React Native. If you run:

  • nx run-android <your-app-name>, it should launch the app in the Android simulator.
  • nx run-ios <your-app-name>, it should launch the app in the iOS simulator.

For server start, you can run:

  • nx start <your-app-name>, it will start the server for the particular app.

👉 Create a Common Library

To create a common library, where you keep common code/logics for both the applications:

This should generate <your_lib> folder under libs.

monorepo_2.jpg

👉 Create a Common Component for both apps

There can be some common components as well that are used across both React Native apps.

nx generate component <your-component-name> --project=ui --export

This generates the folder <your-component-name> under ui/src/lib.

Now you can write your common UI code in the above component and use this component in both the application in app.js.

When you run nx run-ios <your-app-name> and nx run-android <your-app-name>, you should see something like this:

monorepo_3.jpg

Conclusion

Congratulations! You have created React Native mobile apps. 🎉🎉

Nx + React Native is a powerful tool that allows you to have multiple mobile applications code in the same repo with shared business logic.

For Source code, you can check the Github repo.

Happy Coding!😊

Share:
0
+0