Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I install dependencies for a single package when using npm workspaces?

Using npm workspaces I have a folder structure like this

+-- package.json
+-- package-lock.json
+-- client
|   `-- package.json
+-- shared
|   `-- package.json
`-- server
    `-- package.json

Normally when creating a production build for a nodejs app I would run npm ci --only=production and then copy node_modules into a build artifact. I'm not sure how to do something like that when working with workspaces.

If I run npm ci --only=production --workspace server it splits the dependencies across ./node_modules and ./server/node_modules. Maybe I should copy (merge?) both node_modules into a build artifact?

Another option could be to copy ./package-lock.json and ./server/package.json into a fresh directory and run npm ci --only=production. It does seem to work but I don't know enough about npm to know if this is a good idea.

The requirements are:

  1. node_modules should only include production dependencies for the chosen package
  2. The dependency versions should be determined by package-lock.json.
like image 683
joshhunt Avatar asked Sep 08 '25 11:09

joshhunt


1 Answers

According to the available npm options I would suggest a combination of

  • install-strategy (nested)
  • omit (dev)
  • workspace (server)

So from the workspaces root:

npm install --install-strategy=nested --omit=dev --workspace=server

You may or may not need -install-strategy.

This should leave a node_modules directory at the root of the workspaces with only the dependencies defined in the server workspace's package.json file with those defined in devDependencies omitted. You can also --omit=peer to remove peerDependencies from the server workspace as well.

NOTE: Depending on your dependency graph, this could still leave multiple node_modules directories that would require combining to create the artifact, i.e. --install-strategy=nested does not appear to be working correctly for npm workspaces. However, the installed deps should correctly be isolated to the workspace passed in --workspace. Here is an example repo showing how those dependencies could be combined.

like image 153
morganney Avatar answered Sep 11 '25 14:09

morganney