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

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:

package.json
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:

nx.json
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