To add a dependency to a PNPM workspace, follow these steps:
-
Locate the root directory of the workspace: A PNPM workspace is typically defined in a directory containing a
pnpm-workspace.yamlfile. First, navigate to this root directory. -
Select the specific package to which you want to add the dependency: The workspace may contain multiple subprojects or packages. Determine which package to add the dependency to.
-
Add dependencies using
pnpm: Execute thepnpm addcommand to add dependencies. For a production dependency, usepnpm add <dependency name>; for a development dependency, usepnpm add <dependency name> --save-dev.
Here are some specific examples:
-
Add a production dependency to a specific package:
shpnpm add lodash --filter <package name>The
--filter <package name>option specifies which package to add the dependency to. If your workspace package is namedapp, you can run:shpnpm add lodash --filter app -
Add a development dependency to a specific package:
shpnpm add typescript --save-dev --filter <package name>If your package is named
appand you want to add TypeScript as a development dependency, you can run:shpnpm add typescript --save-dev --filter app -
Add a dependency to all packages: If you want to add a dependency to all packages in the workspace, omit the
--filteroption or use a wildcard:shpnpm add axios --filter '*'
Remember that when using pnpm, running the pnpm add command from the workspace root directory with the --filter option not only adds the dependency to the specified package but also locks the version in the pnpm-lock.yaml file, ensuring all packages in the workspace use the same version of the dependency.