Search code examples
npmyarnpkglernayarn-workspaces

How to install npm package in Lerna + Yarn Workspaces repo?


If I want to add dependency to a package, do I need to cd into that directory and run yarn add <package>? Or, is there a command I can run in root directory possibly with a flag like --workspace=<workspace-name>?


Solution

  • You don't need to cd into the package directory and run yarn add <package>. You can use lerna add command with --scope filter option at the root path of your multi-package repository.

    Add a single dependency to matched packages

    For example, add chalk dependency to packages/pkg-a:

     [main] ⚡  npx lerna add chalk --scope pkg-a
    lerna notice cli v3.22.1
    lerna notice filter including "pkg-a"
    lerna info filter [ 'pkg-a' ]
    lerna info Adding chalk in 1 package
    lerna info bootstrap root only
    npm WARN @octokit/plugin-request-log@1.0.3 requires a peer of @octokit/core@>=3 but none is installed. You must install peer dependencies yourself.
    
    added 6 packages from 3 contributors and audited 1319 packages in 4.811s
    found 0 vulnerabilities
    

    After installing, it will add chalk to the dependencies field of packages/pkg-a/package.json file

    {
      "name": "pkg-a",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "node app.js",
        "test": "jest --config jest.config.js"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "chalk": "^4.1.0",
        "express": "^4.17.1"
      }
    }
    

    lerna version:

    [main] ⚡  npx lerna -v     
    3.22.1