List NPM workspaces similar to lerna ls
Asked Answered
E

5

7

I'm looking for an NPM command similar to lerna ls that would print out all workspaces.

For example, let's say I have package1 and package2 in a packages sub-directory and my package.json looks like this:

"workspaces": [
 "./packages/*"
]

I would like to get a list of NPM 7 workspaces. For the example I would expect:

  • packages/package1
  • packages/package2

I was hoping npm ls -p --depth 0 would do this, but unfortunately it's printing out other dependencies as well.

I guess I could use npm ls -json and parse out the top level dependencies. However, I'm hoping there's a better way?

Elul answered 15/11, 2021 at 20:47 Comment(0)
G
13

There's a new way in npm@8:

npm query .workspace | jq -r '.[].location'

Returns the expected result:

packages/package1
packages/package2

Still requires jq, but slightly cleaner than before.

Generative answered 10/4, 2023 at 6:31 Comment(1)
Note: the query command does not exist in the npm bundled with Node.js v16Appellative
D
4

This should work on npm version >= 8

npm ls -ws
Delanty answered 1/10, 2023 at 22:44 Comment(0)
E
2

So for now I'm using JQ for this.

Example: npm ls --production --depth 1 -json | jq -r '.dependencies[].resolved'

For my example this results in:

file:../../packages/package1
file:../../packages/package2

I don't know why it adds ../../ in front of it. So to further improve this: npm ls --production --depth 1 -json | jq -r '.dependencies[].resolved[11:]' returns the expected result:

packages/package1
packages/package2

I've also submitted a feature request here: https://github.com/npm/cli/issues/4086

Elul answered 24/11, 2021 at 3:22 Comment(3)
the ../../ is because it's the path that the symlink uses from the node_modules/@my-scope folder. If you have a non-scoped package in your workspace, it would just be a single ../Hierocracy
npm ls --production --depth 1 -json | jq -r '.dependencies[].resolved' | sed 's/file:\.\.\///'Strati
@Strati this persons sedsCrumple
E
0

Just in case anyone is looking for a pure NodeJS-npm solution:

npm exec -ws -c 'node -e "console.log(require(\"./package.json\").name)"'
Epanorthosis answered 23/10, 2023 at 10:17 Comment(1)
This would actually be really really great, but it's awfully slow.Crumple
G
-1

here is a bash version:

npm pkg get name -ws | grep -o '"@[_0-9a-z-]*/[_0-9a-z-]*":' | tr -d "'\":"

screenshot of work

Geanticline answered 21/3 at 6:58 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Pteranodon

© 2022 - 2024 — McMap. All rights reserved.