8

A few practical use cases for npm dependency queries

 1 year ago
source link: https://pawelgrzybek.com/a-few-practical-use-cases-for-npm-dependency-queries/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

A few practical use cases for npm dependency queries

Published: 2022.10.15 · 2 minutes read

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

Name:
Website (optional):
Twitter (optional):
GitHub (optional):
Comment:

👆 you can use Markdown here

Save my data for the next time I comment


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK