Skip to content

Instantly share code, notes, and snippets.

@fabiospampinato
Last active March 27, 2024 16:38
Show Gist options
  • Save fabiospampinato/ea3c413f4c3a910d077726257ed74a59 to your computer and use it in GitHub Desktop.
Save fabiospampinato/ea3c413f4c3a910d077726257ed74a59 to your computer and use it in GitHub Desktop.
20x faster replacement for "npm run"
# 20x faster replacement for "npm run"
# - It supports scripts executing a built-in shell function
# - It supports scripts executing a binary found in PATH
# - It supports scripts executing a binary found in node_modules
# - It supports passing arguments and options to scripts
# - It supports reading scripts either via ripgrep (fast) or via jq (slower, but safer)
# - It adds ./node_modules/.bin to the $PATH
# - It handles gracefully when a script has not been found
# - It handles gracefully when "&", "&&", "|", "||", or ENV variables are used, falling back to "npm run"
#TODO: Make this work with "&&" too, which would enable this to speed up significantly more scripts
#TODO: Find something that's just as fast as ripgrep, but just as safe as jq
function run () {
local jq_mode=false # Set this to true if you don't want to live dangerously
local script_name="${1:-null}"
if [ "$jq_mode" = true ] || ! command -v rg &> /dev/null; then # ~2x slower, but super safe
local script_value="$(jq -r ".scripts[\"$1\"]" package.json)"
else # Fast
local script_value=$(rg -o "\"$script_name\":\s*\"(.*)\",?$" -r '$1' < package.json)
fi
if [ $script_value = "null" ]; then
echo "Missing script: \"$script_name\""
return 1
else
shift
local script_args=$@
if echo "$script_value" | grep -q '\([&|()]\|[A-Z]=\)'; then # Fallback path
npm run $script_name $script_args
else # Fast path
local npm_bin_path=$(realpath ./node_modules/.bin || echo '')
if [ -n "$npm_bin_path" ]; then
export PATH="./node_modules/.bin:$PATH"
fi
echo "\n> $script_value\n"
local bin_name=${script_value%% *}
local bin_args=${script_value#* }
if [ $script_value = $bin_name ]; then
bin_args=""
fi
if type $bin_name | grep -q 'shell builtin'; then
eval $bin_name $bin_args $script_args
else
local bin_path=$(which $bin_name &> /dev/null && which $bin_name || echo "./node_modules/.bin/$bin_name")
eval $bin_path $bin_args $script_args
fi
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment