Skip to content

Instantly share code, notes, and snippets.

@osteele
Last active October 21, 2021 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osteele/6e70be523b1e33504368eec77b251e7c to your computer and use it in GitHub Desktop.
Save osteele/6e70be523b1e33504368eec77b251e7c to your computer and use it in GitHub Desktop.
Bash alias to run a command in npm or yarn
# Pass arguments to whichever of npm or yarn is managing the current directory's
# workspace.
alias yn=npm/yarn
function npm/yarn() {
local package_manager # this will be initialized to yarn or npm
local dir=$(pwd)
while true; do
if [[ -f "$dir/package.json" ]]; then
if [[ -f "$dir/package-lock.json" ]]; then
package_manager="npm"
break
fi
if [[ -f "$dir/yarn.lock" ]]; then
package_manager="yarn"
break
fi
package_manager="npm"
fi
current_dir=$dir
dir=$(dirname "$dir")
if [[ "$dir" == "/" || "$dir" == "$current_dir" ]]; then
if [[ -z "$package_manager" ]]; then
echo "Error: package.json not found in current working directory or a directory that contains it" 1>&2
return 1
else
echo "Warning: package-lock.json or yarn.lock not found; assuming $package_manager" 1>&2
fi
fi
done
$package_manager $@
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment