Get All NPM Scripts from package.json
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:
[[ -f package.json ]] \
&& jq -r '.scripts | keys' package.json \
|| echo "No package.json file in this dir" >&2
Then I can just type:
and that’s it :)
This is also useful when using
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)
$(SAY) "npm run $@"
@npm run $@
Then I can use either
make to run the same NPM scripts.