Get All NPM Scripts from package.json

Pavel Saman
1 min readJan 18, 2023

When working with package.json files, I often need to get all scripts to find the one I want to run.

To do that, I can either open the file and find the script I need, which is slow, or I can use jq to get all the NPM scripts right on the command line:

$ jq -r '.scripts | keys[]' package.json

To simplify this for the future, let’s put it inside a short Bash function:

npmscripts() {
[[ -f package.json ]] \
&& jq -r '.scripts | keys[]' package.json \
|| echo "No package.json file in this dir" >&2
}

Then I can just type:

$ npmscripts

and that’s it :)

This is also useful when using Make. In Makefile, I can have:

SHELL := bash

COLOR_START = \e[91m\e[1m
COLOR_END = \e[0m
SAY = @printf "$(COLOR_START)%s\n$(COLOR_END)"

TARGETS_NPM_SCRIPTS := $(shell jq -r '.scripts | keys[]' package.json)

.PHONY: $(TARGETS_NPM_SCRIPTS)

$(TARGETS_NPM_SCRIPTS):
$(SAY) "npm run $@"
@npm run $@

Then I can use either npm or make to run the same NPM scripts.

--

--