A monorepo is a version-controlled code repository that holds many projects. While these projects may be related, they are often logically independent and run by different teams. NX is a build system made especially for monorepos and can be extended by plugins. It will make it easier for you to manage your different projects in the monorepo by
- allowing you to run actions (also in parallel or on different machines) for one or more projects without changing directories
- running actions only for affected projects (think of running tests only in projects which actually have code changes)
- cache common operations for a faster 2nd run, to never rebuild the same code twice
- allowing you to quickly set up new apps or libraries
- displaying dependency graphs of your projects
- allowing you to enforce project boundaries via es-lint rules to avoid circular dependencies
- allowing you to write code generators that create template files for you
- integrating itself with editors and IDEs
- automating dependency updates
Package-based repos vs. Integrated repos
Nx differentiates between Integrated repos which make use of NX plugins and package-based repos which only make us of NX’s core features.
Package-based repo | Integrated repo |
---|---|
Package-based repo | Integrated repo |
packages depend on each other’s package.json file | depend on each other through standard import statements |
nested node_modules folder for each package | a single node_modules folder used by all projects |
multiple versions possible defined in a package’s package.json file | a single version of every dependency defined at root |
Build tools like Jest and Webpack work as usual | Build tools like Jest and Webpack might need modification to work |
A new package means creating all the build tooling from scratch | A new project can make use of generated boilerplate setup through NX plugins |
Lerna, Yarn, Lage and Nx (without plugins) support this style | Bazel and Nx (with plugins) support this style |
Easy to adopt with good benefits | Provides more value, especially at a larger scale |
Creating a workspace
An NX workspace is the initial one-time setup for all of your projects in a monorepo. If for example you choose myorg as the workspace name, then a library mylib
can be referenced as @myorg/mylib
.
# create workspace without a preset np create-nx-workspace myorg
# create workspace with a preset npx create-nx-workspace --preset=react
It creates a bunch of folders including apps
and libs
. Apps will contain all code that can be build and deployed. Libs contains libraries that can be used in apps. Libs is where most of the code will be stored.
- There is only one
package.json
in the root folder. workspace.json
contains info about your projects and where they will be build and much more.nx.json
contains config of the nx workspace. You can define tasks here (more about that later).