Skip to content

Software Engineer at Polygon

A few practical use cases for npm dependency queries

I don’t want to joke about the JavaScript ecosystem and its dependencies because we have seen enough of it. Let’s accept that our projects consist of hundreds of third-party modules — when it works, it works fine and pays the bills.

Sometimes we need to get some insights about the packages that we use. For example, what’s the licence of the software we rely on? What is the version of the particular package? How many modules we depend on are created by Sindre Sorhus, and how is that even possible? Manually going through node_modules sounds like a chore, but luckily there is a better way.

The npm query command added to v8.16.0 accepts a CSS-like dependency selector and returns a filtered JSON list of dependencies from your project. Let’s look at a few practical examples that can help us in our day-to-day job.

Basic npm queries #

# List all dependencies
npm query "*"
# List all dependencies with "react" in their name
npm query "[name*=react]"
# List all dependencies with a licence other than MIT
npm query ":not([license=MIT])"
# List all dependencies without dependencies
npm query ":empty"
# List all dependencies that seek funding
npm query ":has([funding])"
# List all packages created by Sindre Sorhus 🦄
npm query ":attr(author, [name=\"Sindre Sorhus\"])"

Advanced npm queries #

The result of the npm query command is unformatted JSON which is OK, but with tools like the jq we can achieve a lot more! Have a look at a few more advanced examples.

# List all dependencies (formatted output)
npm query "*" | jq '.'
# List only names of packages created by Sindre Sorhus 🦄
npm query ":attr(author, [name=\"Sindre Sorhus\"])" | jq '.[] | .name'
# Uninstall all packages with "gulp" in their name
npm query "[name*=gulp]" | jq 'map(.name)|join("\n")' -r | xargs -I {} npm uninstall {}

Some helpful resources #

I hope you liked this brief article. Let me leave you with a list of helpful resources to deepen your knowledge in a field. Until next time, stay groovy 👋

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!