Test many npm packages at once with Lerna

If you develop multiple JavaScript packages, and you already use npm scripts to automate your tests in each package, Lerna can help you run the tests for all packages.

When you tell Lerna to run a script, Lerna reads the script definition from the package.json file in each directory, so Lerna runs the right script even if you define it differently in different packages. That’s very useful, for example to test all packages at once with a single lerna run test command, even if test is defined differently in each package.

You don’t need to replace npm with Lerna. To use Lerna, group all packages under a directory called packages. In the parent directory of the packages directory, create a new package.json with a scripts section that delegates npm commands to Lerna.

"scripts": {
  "init": "lerna init",
  "bootstrap": "lerna bootstrap",
  "test": "lerna run test"

To install the dependencies for each of your packages, there’s a special command: lerna bootstrap. Why? Some packages might not depend just on external packages, but might also depend on each other. To support this case, it’s not enough to just run npm install for every package, because you might want to use the version of a package that you’re developing as a dependency for another package. That’s where lerna bootstrap comes in. lerna bootstrap installs all dependencies and, if one package depends on another in the same directory, lerna bootstrap links the package to the local version.

To recap, here are the steps to test all your packages with Lerna:

  1. Move all your packages to a directory named packages.

  2. In the parent directory, create a package.json file and add Lerna as a devDependencies. You can also specify any common build dependencies (linters, module bundlers) in the same devDependencies field.

  3. Run npm i to install Lerna and its dependencies.

  4. Define the scripts above in the top package.json:

  5. Run npm init. This creates a file that lets you specify the Lerna version and, by default, a common version number for all packages.

  6. Run npm bootstrap to install the dependencies for every package.

  7. Run npm test in the top package.

If you want to install all dependencies from scratch, run lerna clean to delete all already installed dependencies.

Additionally, Lerna can help you publish all your packages at once and keeping their versions in sync, but I have never used that feature (I was originally interested in Lerna to manage the sample code for my React book). Even if you don’t care very much about versions, Lerna’s ability to test a lot of packages at once already saves a lot of time.