Last active
October 21, 2021 06:18
-
-
Save osteele/6e70be523b1e33504368eec77b251e7c to your computer and use it in GitHub Desktop.
Bash alias to run a command in npm or yarn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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