Adding Nx to NPM/Yarn/PNPM Workspace
Migrating from Lerna?Interested in migrating from Lerna in particular? In case you missed it, Lerna v6 is powering Nx underneath. As a result, Lerna gets all the modern features such as caching and task pipelines. Read more on https://lerna.js.org/upgrade.
Nx has first-class support for package-based monorepos. As a result, if you have an existing NPM/Yarn or PNPM-based monorepo setup, you can easily add Nx to get
- fast task scheduling
- support for task pipelines
- caching
- optionally remote caching with Nx Cloud
- optionally distributed task execution with Nx Cloud
This is a low-impact operation because all that needs to be done is to install the nx
package at the root level and add an nx.json
for configuring caching and task pipelines.
Installing Nx
Run the following command to automatically set up Nx:
❯
npx nx@latest init
Running this command will
- collect all the NPM scripts in the corresponding
package.json
files of your workspace packages - ask you which of those scripts are cacheable (e.g. build, test, lint)
- ask you which of those scripts might need to be run in a certain order (e.g. if you run the
build
script you might want to first build all the dependent projects) - ask you for custom output folders that should be captured as part of the caching
This process adds nx
to your package.json
at the root of your workspace:
1{
2 "name": "my-workspace",
3 ...
4 "devDependencies": {
5 ...
6 "nx": "15.3.0"
7 }
8}
9
It also creates a nx.json
based on the answers given during the setup process. This includes cacheable operations as well as some initial definition of the task pipeline. Here is an example:
1{
2 "tasksRunnerOptions": {
3 "default": {
4 "runner": "nx/tasks-runners/default",
5 "options": {
6 "cacheableOperations": ["build", "test", "lint"]
7 }
8 }
9 },
10 "targetDefaults": {
11 "build": {
12 "dependsOn": ["^build"]
13 }
14 }
15}
16
Incrementally Adopting Nx
In a package-based monorepo, Nx only manages the scheduling and caching of your npm scripts. Hence, it can easily be adopted incrementally by initially using Nx just for a subset of your scripts and then gradually adding more.
For example, use Nx to run your builds:
❯
npx nx run-many -t build
But instead keep using NPM/Yarn/PNPM workspace commands for your tests and other scripts. Here's an example of using PNPM commands to run tests across packages
❯
pnpm run -r test
This allows for incrementally adopting Nx in your existing workspace.
Learn More
Learn more about how caching works
Learn more about how to setup task dependencies
Learn about how to ignore certain projects using .nxignore
Read about how Nx compares to Turborepo
Read about how Nx and Lerna can be used together
Learn about two styles of monorepos.