pnpmpnpm-workspace

Efficiently Managing Shared Dependencies and Binaries in a pnpm Monorepo Workspace


I'm working on a monorepo setup using pnpm workspaces to manage multiple related projects. My goal is to efficiently manage and share dependencies across these projects without duplicating them in each project's package.json. However, I'm facing challenges with resolving shared dependencies and ensuring that binaries are correctly executed.

Context:

  1. Shared Dependencies: I want to maintain a set of common dependencies that can be used across different projects without listing them in every single package.json. This helps avoid redundancy and ensures consistency.
  2. Binary Resolution: Some dependencies provide binaries (e.g., rimraf) that need to be available when running scripts in individual projects. These binaries need to be correctly resolved, even if they are defined in a shared or root configuration.
  3. Avoiding Dependency Bloat: Not all projects in the monorepo require all shared dependencies, so I want to avoid bloating each project's package.json or the root package.json with unnecessary dependencies.
  4. Modular Configurations: I prefer a modular approach where shared configurations and dependencies can be managed centrally but linked or used as needed in individual projects.

Current Setup:

Issues:

  1. Binaries Not Found: When running scripts in individual packages, binaries like rimraf are not found unless they are explicitly listed in each package's devDependencies.
  2. Shared Libraries: Dependencies like @faker-js/faker in the shared package are not being resolved by other packages, such as api-package, even though they are intended to be shared.

Questions:

  1. How can I ensure that binaries from shared dependencies are correctly resolved and executed in individual package scripts?
  2. What is the best way to manage shared dependencies to avoid duplication and bloat, but still ensure they are available where needed?
  3. Are there any best practices or configurations for pnpm workspaces to handle this efficiently?

Is this even possible with pnpm workspaces, or am I trying to achieve something that isn't feasible?

Any guidance or examples of how to set this up effectively would be greatly appreciated!


Solution

  • That is not possible. You cannot share dependencies like this. You cannot access dependencies of dependencies. If these are dev dependencies, just add them to the root package.json. Otherwise, you need to duplicate the dependencies wherever you use them. You can use catalogs to sync the versions of such dependencies across the workspace.

    There was a rejected RFC to support something similar. Core npm/node.js contributors said it was a bad idea.

    If you want a way to share dependencies, you could also check Bit workspace. Bit has environment components, which allow to share dependencies the way you want.