Create a package-based Monorepo with Nx

Kyle Le
Bits and Pieces
Published in
4 min readOct 22, 2022

--

What is a Monorepo?

A Monorepo or Monorepository is a code management and architectural concept where you keep all your code in one super repository instead of managing multiple smaller repositories — like a single repository for your website and libraries

About NX

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

Nx supports package-based repo with or intergrated repo that has pre-configured setup.

Getting started

To begin with Monorepos, I suggest newcomers to choose the package-based way. So we can learn how to build things our way and easy to do modifications.

Create a new workspace

We run this command:

npx create-nx-workspace@latest package-based --preset=npm

Then we will have the following structure

In the packages folder, we can set up every package with any framework you want to, for example, I will create 2 React packages, one for my app, and one for my UI and utilities kit

Linking our packages

Now you can import files from other packages like every other library. For instance, I will import constants and components from my common-ui package:

Easy right ? To optimize our monorepo, we need to understand my web package has a dependency is common-ui that we have to install it first. But what if common-ui hasn’t been build yet ?

To make sure common-ui has to be built before web builds, we put this into our nx.json

{ 
targetDefaults:
{ build: {
dependsOn:
['^build']
}
}
}

So every web dependencies has to be built before web builds

Nx cached everything

My package.json

We can decide which package to build, or build them all. If you run nx run many , Nx will cache the results to reduce build time

Conclusion

This is just a simple guide, I hope this can help you speed up your existing workflow with minimum effort. You can check out my source code here.

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

Build apps with reusable components like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--

I’m a Software Engineer who loves to write. My content is based on what I've learned and experienced every day