Search code examples
monorepopnpm

pnpm -- sync versions of dependencies


Let's say I have the following stricture for a Javascript monorepo

-- module a
   package.json
-- module b
   package.json
package.json

Module A and Module B both depend on lodash.

With pnpm, is there any way to ensure that they both use the same version of lodash? Like perhaps installing lodash in the root directory and saying "use whatever version is in the root of the workspace"?

P.S. I know that pnpm allows or workspaces, but to my understanding (which can be wrong), that's only used if the dependencies are already a module in the monorepo — not for 3rd-party dependencies.


Solution

  • You can use the overrides field in the package.json at the root of your project to achieve this.

    https://pnpm.io/package_json#pnpmoverrides

    {
      "pnpm": {
        "overrides": {
          "lodash": "4.17.20"
        }
      }
    }
    

    This will enforce the version of lodash for all the packages in your workspace that depend on it.

    A similar feature exists in Yarn, called resolutions. Apparently there are some differences, though I'm not familiar with the specifics. The feature was added here.

    Update - alternative approach

    You can also try syncpack if the overrides solution doesn't sit well with you. At my organization we're slowly moving towards syncpack for issues where the dependencies are only requested by our monorepo packages; the rationale for this is that too many overrides were accumulating over time.

    But for ensuring the versions of dependencies of dependencies, overrides is still what you need.

    e.g. if you install react-dom and it depends on scheduler and you need a specific version of scheduler for some reason, then the overrides approach is your only option - syncpack can't help there.