Question

NPM 7 workspaces - how to install new package in workspace?

If I have a NPM 7 workspace like this:

root
   - submodule0
   - submodule1
   - submodule2

and I navigate to the submodule0 directory and run npm i somepackage it seems to "break" the workspace by creating a new package-lock.json in the submodule0 directory and installing all the dependencies there. In other words, it just does the old behavior that existed before I created the workspace. I was hoping for a command similar to lerna where I can install a new package in submodule0 from the root. Something like:

npm i somepackage --scope submodule0

So far, the only workaround I can find is to edit the submodule0 package.json and add the somepackage manually. Then run npm i from the root. Obviously this is not ideal because I need to look up the @latest version, navigate to the subdirectory, open the package.json, etc. etc. as opposed to just typing one line in the root.

 46  49743  46
1 Jan 1970

Solution

 60

Workspace support for npm install and npm uninstall was added in npm v7.14.0. You can now just do:

npm i somepackage --workspace=submodule0

Uninstalling modules has been the biggest pain, so this is really exciting. The npm team seems to be slowly adding support to commands one by one. Follow updates here: https://github.com/npm/cli/blob/latest/CHANGELOG.md.

2021-05-24

Solution

 11

I'm also baffled with why npm workspaces has been released without this functionality.

My current workaround uses the add-dependencies package, which adds dependencies to a declared package.json file, whilst skipping the installation process.

npm i add-dependencies -g

Then, from top level of the monorepo, you can run:

npx add-dependencies ./submodule0/package.json somepackage && npm i

Hopefully a --workspace argument will be added to npm i soon to avoid this faff.

2021-01-10