DEV Community

Cover image for Create a package-based Monorepo with Nx
Duc Le
Duc Le

Posted on


Create a package-based Monorepo with Nx

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
Image description

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

Then we will have the following structure

Image description

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

Image description

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:

Image description

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

  { build: { 
Enter fullscreen mode Exit fullscreen mode

So every web dependencies has to be built before web builds

Nx cached everything
My package.json

Image description

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


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

Oldest comments (1)

leomoyano profile image
Leonardo Moyano

Hey, I have a silly doubt about it, when I want to create the application or library within the package folder, what's the command should I use? nx g @nrwl/react:app ? Thanks!

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post