Tech

Write Once, Run Anywhere: The Amazing Benefits of Monorepos

By Naveed SarwarDecember 5th 2023

Write Once, Run Anywhere: The Amazing Benefits of Monorepos


Write Once, Run Anywhere: The Amazing Benefits of Monorepos

In the ever-evolving realm of software development, monorepos, or monolithic repositories, have risen as a game-changing solution for managing diverse projects within a unified version control system. Distinct from conventional polyrepos (multiple repositories) and monoliths (single, large repositories), monorepos present a unique set of advantages and challenges that profoundly influence development workflows.

TechloSet Solutions specializes in developing and maintaining monorepos for web and mobile applications. Our team of experts can help you leverage the power of monorepos to streamline your development process and enhance code quality. Learn more about our services and contact us today to get started.

What is a Monorepo?

A monorepo stands as a centralized version control repository that consolidates multiple projects or applications within a single directory. Unlike polyrepos, which involve managing separate repositories, and monoliths, which house all code in a single repository, monorepos strike a balance between organization and code sharing.

Advantages of Monorepos

Code Reuse

At the forefront of monorepo advantages is the seamless sharing and reuse of code across different projects. This promotes consistency, accelerates development cycles, and ensures that updates to shared components propagate effortlessly throughout the entire codebase.

Dependency Management

Monorepos simplify dependency tracking, ensuring consistent versions across projects. Centralized dependency management minimizes version conflicts, providing a stable foundation for applications.

Cross-Project Testing

Monorepos facilitate comprehensive testing across multiple projects within a unified environment. This holistic testing approach helps identify and address potential issues early in the development process, enhancing overall code quality and reliability.

Continuous Integration

Streamlining integration and deployment processes is a key benefit of monorepos. With all projects housed in a single repository, automated workflows, such as those provided by GitHub Actions, can be applied uniformly across the entire codebase.

Challenges of Monorepos

Scalability

Managing a growing codebase within a monorepo can become challenging. Ensuring scalability requires careful consideration of tools and strategies to maintain organization and performance.

Performance

Large codebases may experience slower build and test times. Optimizing performance becomes crucial to maintaining developer productivity and efficient CI/CD pipelines.

Tooling

Specialized tools are necessary to manage the complexity of a monorepo effectively. A well-thought-out tooling strategy is essential for mitigating challenges and enhancing development workflows.

Collaboration

Effective collaboration between development teams is crucial to avoid conflicts and ensure a smooth development experience. Coordinating efforts becomes increasingly important as the number of contributors grows.

Tutorial Goal

The primary objective of this tutorial is to guide developers through the process of setting up and utilizing a monorepo for a web development project. The example project, implemented with React, Next.js, and GraphQL, serves as a practical illustration of the discussed concepts.

Monorepo Tools and Concepts

Common Tools and Concepts

  1. Git
  2. Yarn
  3. Babel
  4. ESLint
  5. Vercel
  6. Solito

Tool Usage

  • Git: Ensures version control and collaboration by tracking changes and managing branches effectively.

  • Yarn: Manages dependencies consistently, providing a centralized solution for package installations.

  • Babel: Transpiles code to ensure compatibility across different packages, promoting a seamless development experience.

  • ESLint: Enforces coding standards and catches potential issues early in the development cycle, enhancing overall code quality.

  • Vercel: Provides automated publishing and deployment capabilities, streamlining the development process.

  • Solito: Enables code sharing across platforms, ensuring a consistent user experience.

Creating a Simple Monorepo

Setting Up and Using Tools

The tutorial below guides you all through the process of setting up a monorepo structure from initialization to phase. The example project is implemented with React, Next.js, React Native and Solito, and serves as a practical illustration of the discussed concepts.

Initialize Monorepo

It is kind of tiresome to create a monorepo from scratch. So, we will use a tool called Solito to initialize our monorepo. Solito is a CLI tool that helps you to create a monorepo with a single command. It also helps you to add new packages to your monorepo. To install Solito, run the following command in your terminal we also created a template for you to use, you can clone it and start the project.

git clone https://github.com/techloset/solito-monorepo-template

or install it via yarn

npx create-solito-app@latest -t with-expo-router

Building, Running, and Testing with Yarn

Utilize the capabilities of Yarn to facilitate the development process by independently building, running, and testing each package. This approach ensures a well-organized development workflow while maintaining the autonomy of individual packages.

1. Install Dependencies

yarn

2. Run Next.js Locally

For local development with Next.js, execute the following command:

yarn web

This internally runs yarn next.

3. Run Expo Locally

Navigate to the Expo package directory for local development:

cd apps/expo

Build the development client on your device or simulator using either of the following:

expo run:ios

or

eas build

After building the development client, return to the root of the monorepo and run:

yarn native

Publishing and Deployment

The final stages of the tutorial encompass the use of Vercel for automated publishing and deployment. These steps establish a systematic and reliable approach to managing changes and deploying applications within the monorepo.

Build Android App for Expo

Navigate to the Android directory within the Expo app and execute:

cd apps/expo/android
./gradlew assembleRelease

Deploy Web App with Vercel

Utilize Vercel for seamless web deployment with minimal configuration. To deploy the web app, follow these steps:

  1. Push your code to GitHub.
  2. Assuming you have a Vercel account, log in to Vercel dashboard, and click on New Project.
  3. Select your GitHub repository.
  4. Select Import Project.
  5. Select Next.js as your framework.
  6. Select Root Directory as apps/next.
  7. Leave the rest of the settings as default and click on Deploy.

Deploy Web App with Firebase

Assuming you are in your root Next.js app directory, we can deploy our app to Firebase by following these steps:

  1. Create a Firebase project.
  2. Install Firebase CLI.
  3. Select your preferred Firebase project and settings.
  4. Do not forget to select firebase public directory as apps/next/out
  5. Add the following to your packages.json file:
{
  "scripts": {
    "export": "next export"
  }
}

run following to build and then export your Next.js app

yarn build && yarn export

it will create a out directory in your apps/next directory.

  1. Run the following command to deploy your app:
firebase deploy

Voila! Your first Nextjs monorepo app is deployed.

These steps ensure a streamlined development and deployment process, enhancing the efficiency and reliability of your monorepo setup.

Monorepo Structure

/
|-- apps
|   |-- expo
|   |   |-- app
|   |       |-- (files for iOS and Android)
|   |
|   |-- next
|       |-- app
|           |-- (files for Next.js app)
|
|-- packages
    |-- app
        |-- (files shared across apps)
        |
        |-- features
        |   |-- (feature-specific files)
        |
        |-- provider
            |-- (provider files, including no-ops for Web)

You can add other folders inside of packages/ if you know what you're doing and have a good reason to.

Best Practices

  1. Consistent Tooling:

    • Ensure that all projects within the monorepo use consistent tooling. This includes version control systems (e.g., Git), package managers (e.g., Yarn or npm), and coding standards. Consistency minimizes friction between projects and streamlines development workflows.
  2. Code Reusability:

    • Leverage the advantages of a monorepo by encouraging code reuse. Identify common functionalities or components that can be shared across projects, promoting modularity and reducing duplication of code.
  3. Dependency Validation:

    • Use tools like Manypkg to validate dependencies across packages. Dependency validation helps catch issues early, ensuring that all packages within the monorepo use compatible versions of dependencies.
  4. Versioning and Changesets:

    • Implement a versioning strategy for packages within the monorepo. Tools like Changesets make it easier to manage version bumps and generate changelogs. Consistent versioning aids in tracking changes and maintaining compatibility.
  5. Type Safety:

    • Consider incorporating TypeScript for enhanced type safety. Strong typing reduces the likelihood of runtime errors and provides better developer tooling, making it easier to understand and maintain the codebase.
  6. Automated Testing:

    • Implement automated testing for all projects within the monorepo. CI/CD pipelines should include comprehensive test suites to catch issues early in the development process. This ensures code reliability and facilitates continuous integration.
  7. Modular Architecture:

    • Structure your monorepo in a modular fashion. Divide the codebase into logical packages or modules, each responsible for a specific functionality. This modular approach enhances maintainability and makes it easier for developers to understand and contribute to the codebase.
  8. Continuous Integration and Deployment (CI/CD):

    • Establish CI/CD pipelines to automate the build, test, and deployment processes. CI/CD ensures that changes are validated and deployed consistently, reducing manual intervention and the likelihood of deployment errors.

Learning Resources

  • Monorepo Explained: A website providing an overview of monorepos, their usefulness, and the tools to build them. It compares features and advantages of different monorepo tools.

  • Monorepo - Wikipedia: An article offering a brief history and definition of monorepos, examples of companies and projects using them, and discussions on benefits and challenges.

  • Solito with Fernando Rojo: A podcast with Founder of Solito explaining how learning React Native produced the idea for Solito, how Solito lets you use the same code in a React website as a React Native website.

Conclusion

Monorepos offer a potent solution for managing multiple projects within a single repository. The example project, implemented with React, React Native, and Next.js, demonstrates the practical application of monorepo principles and tools. The tutorial guides developers through the process of setting up and utilizing a monorepo for a web development project, highlighting the advantages and challenges of this approach.

Globe

COPYRIGHT © 2024 TECHLOSET. ALL RIGHTS RESERVED.